Question

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

Thinking:

  • Method 1:递归,回溯
    • 我们如果只是用null作为会输终结的位置,我们会把每个结果都重复一此,所以我们需要进行判断。
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public List<List<Integer>> pathSum(TreeNode root, int sum) {
        List<List<Integer>> result = new ArrayList<>();
        if(root == null) return result;
        pathSum(root, sum, 0, result, new ArrayList<Integer>());
        return result;
    }
    private static void pathSum(TreeNode root, int sum, int count, List<List<Integer>> result, List<Integer> list){
        if(root == null){
            if(count == sum){
                result.add(new ArrayList<Integer>(list));
            }
        }else{
            list.add(root.val);
            if(root.left == null && root.right == null){
                pathSum(root.left, sum, count + root.val, result, list);
                list.remove(list.size() - 1);
            }else if(root.left != null && root.right == null){
                pathSum(root.left, sum, count + root.val, result, list);
                list.remove(list.size() - 1);
            }else if(root.right != null && root.left == null){
                pathSum(root.right, sum, count + root.val, result, list);
                list.remove(list.size() - 1);
            }else{
                pathSum(root.left, sum, count + root.val, result, list);
                pathSum(root.right, sum, count + root.val, result, list);
                list.remove(list.size() - 1);
            }
        }
    }
}

二刷

递归,尽量将复用的代码抽取出来。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public List<List<Integer>> pathSum(TreeNode root, int sum) {
        List<List<Integer>> result = new LinkedList<>();
        if(root == null) return result;
        pathSum(root, result, new LinkedList<Integer>(), 0, sum);
        return result;
    }
    private void pathSum(TreeNode node, List<List<Integer>> result, List<Integer> temp, int count, int sum){
        temp.add(node.val);
        if(node.left == null && node.right == null){
            if(count + node.val == sum){
                result.add(new LinkedList<Integer>(temp));
            }
        }
        if(node.left != null)
            pathSum(node.left, result, temp, count + node.val, sum);
        if(node.right != null)
            pathSum(node.right, result, temp, count + node.val, sum);
        temp.remove(temp.size() - 1);
    }
}