Fork me on GitHub

[leetcode-113-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]
]
Subscribe to see which companies asked this question.

思路:

保存当前遍历的路径,判断当前是否到达根部,而且路径和是否与sum相等。

如果满足条件,将当前路径保存到最后结果里。

如果不满足,先进入左子树 然后右子树判断 ,判断完左子树和右子树后,把开始保存的路径值弹出,向上进行回溯。

 

    void pathSum(TreeNode* root, int sum, vector<vector<int>>& result,vector<int>&path)
    {
        if (root == NULL) return;
        path.push_back(root->val);//暂时放入当前路径中保存
        if (root->left == NULL && root->right == NULL && root->val == sum)//找到路径
        {
            result.push_back(path);
        }
        pathSum(root->left, sum - root->val, result, path);
        pathSum(root->right,sum - root->val, result, path);

        path.pop_back();//弹出 回溯
    }
    vector<vector<int>> pathSum(TreeNode* root, int sum)
    {
        vector<vector<int>> result;
        vector<int> path; 
        
        pathSum(root, sum, result, path);
        return result;
    }

 参考:

https://discuss.leetcode.com/topic/18454/12ms-11-lines-c-solution

posted @ 2017-03-02 10:08  hellowOOOrld  阅读(168)  评论(0编辑  收藏  举报