Thursday, January 15, 2015

Path Sum II (LeetCode Tree)

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

Idea: Classic depth-first search problem. Keep going down the tree until reach a leaf, if the leaf's value equals the target, add the value to the path and add the path to the result. When the search goes up, do not forget to pop the current value from the path since the next search is in another route.

Time: O(n) Space: O(lgn)

Code:
 public class Solution {  
   public List<List<Integer>> pathSum(TreeNode root, int sum) {  
     List<List<Integer>> result=new ArrayList<List<Integer>>();  
     List<Integer> path=new ArrayList<Integer>();  
     dfs(result,path,root,sum);  
     return result;  
   }  
   public void dfs(List<List<Integer>> result,List<Integer> path, TreeNode cur, int target)  
   {  
     if(cur==null)  
       return;  
     if(cur.left==null&&cur.right==null)  
     {  
       if(cur.val==target)  
       {  
         path.add(cur.val);  
         result.add(new ArrayList<Integer>(path));  
         path.remove(path.size()-1);  
       }  
       return;  
     }  
     path.add(cur.val);  
     dfs(result,path,cur.left,target-cur.val);  
     dfs(result,path,cur.right,target-cur.val);  
     path.remove(path.size()-1);  
   }  
 }  

No comments:

Post a Comment