LeetCode(113)——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.

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

AC:

public List<List<Integer>> pathSum(TreeNode root, int sum) {
        List<List<Integer>> resultList = new LinkedList<>();
        
        helper(resultList, root, sum, new ArrayList<>());
        
        return resultList;
    }
    
    private void helper(List<List<Integer>> resultList, TreeNode root, int sum, List<Integer> valueList) {
        if (root == null) {
            return;
        }
        
        valueList.add(root.val);
        
        if (root.val == sum && root.left == null && root.right == null) {
            resultList.add(new ArrayList<>(valueList));
        }
        
        helper(resultList, root.left, sum - root.val, valueList);
        
        helper(resultList, root.right, sum - root.val, valueList);
        
        valueList.remove(valueList.size() - 1);
    }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章