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

思想:用dfs思想求解

注意事项: 对标记节点,要控制回退

java代码:
  1. ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();
  2. ArrayList<Integer> cur = new ArrayList<Integer>();
  3. void pathSumHelper(TreeNode root,int sum) {
  4. if(root==null) return; //注意判断
  5. cur.add(root.val);
  6. if(root.left == null && root.right == null) {
  7. if(root.val == sum) {
  8. res.add(new ArrayList<Integer>(cur));
  9. }
  10. cur.remove(cur.size()-1); //注意回退
  11. return;
  12. }
  13. pathSumHelper(root.left,sum-root.val);
  14. pathSumHelper(root.right,sum-root.val);
  15. cur.remove(cur.size()-1); //注意回退
  16. }
  17. public ArrayList<ArrayList<Integer>> pathSum(TreeNode root, int sum) {
  18. if(root==null) return res;
  19. pathSumHelper(root,sum);
  20. return res;
  21. }
posted @ 2014-07-09 23:32  purejade  阅读(84)  评论(0)    收藏  举报