首页 > 其他 > 详细

Path Sum II (Find Path in Tree) -- LeetCode

时间:2016-01-30 18:08:02      阅读:168      评论: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]
]
 
思路:简单的DFS。要注意的一点是,所有的路径必须到达叶子结点才算数。叶子结点的定义是没有孩子的节点。假如root节点没有孩子节点,则root节点就算是叶子结点。但当root节点有一个左孩子节点却没有右孩子节点时,它就不能算是叶子节点了。
 1 class Solution {
 2 public:
 3     void help(vector<vector<int> >& res, TreeNode* root, vector<int>& path, int target)
 4     {
 5         TreeNode *left = root->left, *right = root->right;
 6         path.push_back(root->val);
 7         if (!left && !right && target == root->val)
 8             res.push_back(path);
 9         if (left)
10             help(res, left, path, target - root->val);
11         if (right)
12             help(res, right, path, target - root->val);
13         path.pop_back();
14     }
15     vector<vector<int>> pathSum(TreeNode* root, int sum) {
16         vector<vector<int> > res;
17         if (!root) return res;
18         vector<int> path;
19         help(res, root, path, sum);
20         return res;
21     }
22 };

 

 

 

Path Sum II (Find Path in Tree) -- LeetCode

原文:http://www.cnblogs.com/fenshen371/p/5170950.html

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