程序媛詹妮弗
终身学习

Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.

Note: A leaf is a node with no children.

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

 

题意:

二叉树之和,返回所有和等于给定值的路径

 

思路:

要穷举所有路径。 backtracking。

思路类似two sum, 通过(sum - 当前值) 来check 叶子节点的值是否与一路作减法的sum值相等

 

代码:

 1 class Solution {
 2       public List<List<Integer>> pathSum(TreeNode root, int sum) {
 3         List<List<Integer>> result = new ArrayList<>();
 4         ArrayList<Integer>  cur = new ArrayList<>(); // 中间结果
 5         helper(root, sum, cur, result);
 6         return result;
 7      }
 8     
 9     
10     private static void helper(TreeNode root, int sum, ArrayList<Integer> cur,
11                                 List<List<Integer>> result) {
12         if (root == null) return;
13 
14         cur.add(root.val);
15 
16         // leaf node 
17         if (root.left == null && root.right == null) {
18             if (sum == root.val)
19              result.add(new ArrayList<>(cur));
20         }
21         
22         helper(root.left, sum - root.val, cur, result);
23         helper(root.right, sum - root.val, cur, result);
24 
25         cur.remove(cur.size() - 1);
26     }
27 }

 

posted on 2018-06-09 09:22  程序媛詹妮弗  阅读(128)  评论(0编辑  收藏  举报