Saturday, January 10, 2015

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.
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]
]
/**
 * 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) {
        // Adopt depth first search
        List<List<Integer>> pathList = new LinkedList<>();
        List<Integer> path = new LinkedList<>();
    
        dfs(root, sum, pathList, path);
    
        return pathList;
  }

  public void dfs(TreeNode node, int sum, List<List<Integer>> pathList, List<Integer> path)
  {
        if (node == null)
            return;
        
        path.add(node.val);
        
        if(node.left==null && node.right==null)
            if (node.val == sum)
            {
                // Copy qualified "path" to "newPath"
                List<Integer> newPath = new LinkedList<>(path);
                pathList.add(newPath);
            }
            
        dfs(node.left, sum-node.val, pathList, path);
        dfs(node.right, sum-node.val, pathList, path);

        // Remove this node from path
        path.remove(path.size()-1);
  }
}

No comments:

Post a Comment