首页 > 其他 > 详细

LeetCode---- 二叉树中,找出和为某值的所有路径

时间:2014-02-25 17:21:41      阅读:383      评论:0      收藏:0      [点我收藏+]

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

分析:

这题并不难。其实就是深搜。

就是可能一开始,觉得函数递归的时候,要传哪些参数下去?要返回那些值??  

当有多个返回值的时候怎么办??

    Trick:  C++ 中可以采用引用,来返回值的功能。


1. 返回值: 多条 paths, 可以将 vector<vector<int> >& result 作为形参;  这样其实 所有的递归函数都共享了这个 vector; 当找到路径时,push_back即可。

2. 需要往下传的参数: sum,   当前的路径;

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    vector<vector<int> > pathSum(TreeNode *root, int sum) {
        vector<vector<int> > result;
        vector<int> path;
        
        MyPathSum(root, sum, path, result);
        
        return result;
    }
private:
    void MyPathSum(TreeNode *root, int sum, vector<int> &path, vector<vector<int> > &result)
    {
        if(root == NULL) return;
        
        path.push_back(root->val);
        if(root->left == NULL && root->right == NULL){
            if(sum == root->val){
                result.push_back(path);
            }
        }
        
        if(root->left){
            MyPathSum(root->left, sum - root->val, path, result);
        }
        
        if(root->right){
            MyPathSum(root->right, sum - root->val, path, result);
        }
        path.pop_back();
    }
};


LeetCode---- 二叉树中,找出和为某值的所有路径

原文:http://blog.csdn.net/shoulinjun/article/details/19841151

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!