• Path Sum II


    Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.

    For example:
    Given the below binary tree and sum = 22,
                  5
                 / 
                4   8
               /   / 
              11  13  4
             /      / 
            7    2  5   1
    

    return

    [
       [5,4,11,2],
       [5,8,4,5]
    ]
    

    Analyse: recursively do the left and right part. When a fraction meets the requirement, push it into the result.

    Runtime: 12ms.

     1 /**
     2  * Definition for a binary tree node.
     3  * struct TreeNode {
     4  *     int val;
     5  *     TreeNode *left;
     6  *     TreeNode *right;
     7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     8  * };
     9  */
    10 class Solution {
    11 public:
    12     vector<vector<int> > pathSum(TreeNode* root, int sum) {
    13         vector<vector<int> > result;
    14         if(!root) return result;
    15         
    16         vector<int> temp;
    17         path(root, sum, result, temp);
    18         return result;
    19     }
    20     void path(TreeNode* root, int gap, vector<vector<int> >& result, vector<int>& temp){
    21         if(!root) return;
    22         
    23         temp.push_back(root->val);
    24         if(!root->left && !root->right){
    25             if(root->val == gap) result.push_back(temp);
    26         }
    27         path(root->left, gap - root->val, result, temp);
    28         path(root->right, gap - root->val, result, temp);
    29         
    30         temp.pop_back();
    31     }
    32 };
  • 相关阅读:
    ftp
    vmware虚拟机如何安装ubuntu14.10系统
    第1章 初识java----Java简介
    fiddler
    Program Files 与Program Files (x86)
    跟我一起认识axure(三)
    React-FlipOver-Counter(日历翻页)
    vue2-vux-fitness-project
    cloud-music
    跟我一起认识axure(二)
  • 原文地址:https://www.cnblogs.com/amazingzoe/p/4694861.html
Copyright © 2020-2023  润新知