LeetCode 39 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]
]
분석:
두 갈래 나무를 보고 돌아오고 싶은데,
find all 을 보고 돌이켜 보고 싶고 DFS 가 생각납니다.
/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public List<List<Integer>> pathSum(TreeNode root, int sum) {
        List<List<Integer>> result = new ArrayList<List<Integer>>();
        if(root == null) return result;
        List<Integer> curr = new ArrayList<Integer>();
        curr.add(root.val);
        dfs(root, sum-root.val, curr, result);
        return result;
    }
    
    private void dfs(TreeNode node, int remain, List<Integer> curr, List<List<Integer>> result){
        if(node == null) return;
        if(node.left==null && node.right==null && remain == 0){
            result.add(new ArrayList<Integer>(curr));
            return;
        }
        if(node.left != null){
            curr.add(node.left.val);
            dfs(node.left, remain-node.left.val, curr, result);
            curr.remove(curr.size()-1);
        }
        if(node.right != null){
            curr.add(node.right.val);
            dfs(node.right, remain-node.right.val, curr, result);
            curr.remove(curr.size()-1);
        }
        
        
    }
}

좋은 웹페이지 즐겨찾기