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

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 };

 

 

 

posted @ 2016-01-30 14:05  fenshen371  阅读(187)  评论(0编辑  收藏  举报