现在的位置: 首页 > 综合 > 正文

Path Sum II

2017年12月23日 ⁄ 综合 ⁄ 共 871字 ⁄ 字号 评论关闭

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]
]

拿上一题的代码改一下就好了

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
 #define vi vector<int>
 #define vvi vector<vi >
class Solution {
public:
    vector<vector<int> > pathSum(TreeNode *root, int sum) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        vvi ans;
        vi path;
        if (!root)
            return ans;
        getPath(root,sum,ans,path);
        return ans;
    }
    void getPath(TreeNode* root,int sum,vvi& ans,vi& path)
    {
        if (!root)
            return;
        int exp=sum-root->val;
        path.push_back(root->val);
        if (exp==0&&!root->left&&!root->right)  //leaf , found
        {
            ans.push_back(path);
            path.pop_back();
            return;
        }    
        getPath(root->left,exp,ans,path);
        getPath(root->right,exp,ans,path);
        path.pop_back();
        return;
    }
};

 

【上篇】
【下篇】

抱歉!评论已关闭.