首页 > 其他 > 详细

二叉树的路径和

时间:2016-01-19 21:06:31      阅读:169      评论:0      收藏:0      [点我收藏+]

给定一个二叉树,找出所有路径中各节点相加总和等于给定 目标值 的路径。

一个有效的路径,指的是从根节点到叶节点的路径。

给定一个二叉树,和 目标值 = 5:

     1
    /    2   4
  /  2   3

返回:

[
  [1, 2, 2],
  [1, 4]
]

Traverse

 1 /**
 2  * Definition of TreeNode:
 3  * class TreeNode {
 4  * public:
 5  *     int val;
 6  *     TreeNode *left, *right;
 7  *     TreeNode(int val) {
 8  *         this->val = val;
 9  *         this->left = this->right = NULL;
10  *     }
11  * }
12  */
13 class Solution {
14 public:
15     /**
16      * @param root the root of binary tree
17      * @param target an integer
18      * @return all valid paths
19      */
20     vector<vector<int>> binaryTreePathSum(TreeNode *root, int target) {
21         vector<vector<int>> res;
22         helper(root, target, vector<int>(), res);
23         return res;
24     }
25     
26     void helper(TreeNode *root, int target, vector<int> cur, vector<vector<int>> & res) {
27         if (root == NULL) {
28             return;
29         }
30         
31         cur.push_back(root->val);
32         helper(root->left, target - root->val, cur, res);
33         helper(root->right, target - root->val, cur, res);
34         
35         if (target - root->val == 0) {
36             res.push_back(cur);
37         }
38     }
39 };

 

Divide and Conquer

 1 /**
 2  * Definition of TreeNode:
 3  * class TreeNode {
 4  * public:
 5  *     int val;
 6  *     TreeNode *left, *right;
 7  *     TreeNode(int val) {
 8  *         this->val = val;
 9  *         this->left = this->right = NULL;
10  *     }
11  * }
12  */
13 class Solution {
14 public:
15     /**
16      * @param root the root of binary tree
17      * @param target an integer
18      * @return all valid paths
19      */
20     vector<vector<int>> binaryTreePathSum(TreeNode *root, int target) {
21         if (root == NULL) {
22             return vector<vector<int>>();
23         }
24         
25         if (root->val == target && root->left == NULL && root->right == NULL) {
26             return vector<vector<int>>(1, vector<int>(1, target));
27         }
28         
29         vector<vector<int>> left = binaryTreePathSum(root->left, target - root->val);
30         vector<vector<int>> right = binaryTreePathSum(root->right, target - root->val);
31         
32         left.insert(left.end(), right.begin(), right.end());
33         for (int i = 0; i < left.size(); i ++) {
34             left[i].insert(left[i].begin(), root->val);
35         }
36         
37         return left;
38     }
39 };

二叉树的路径和

原文:http://www.cnblogs.com/whlsai/p/5143295.html

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