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

相对于普通的dfs有个增添,不满足要求返回时有个删除的操作。
/**
 * Definition for a binary tree node.
 * 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>> ans=new ArrayList<List<Integer>>();
        if(root==null)
        return ans;
        List<Integer> temp = new ArrayList<Integer>();
        dfs(root,ans,temp,sum);
        return ans;
    }
    
    public void dfs(TreeNode root,List<List<Integer>> ans,List<Integer> temp,int sum){
         if(root.left == null && root.right == null)  
        {  
            temp.add(root.val);  
            int sum1 = 0;  
            for(int i = 0; i < temp.size(); i++)  
            {  
                sum1 += temp.get(i);  
            }  
            if(sum1 == sum)  
                ans.add(new ArrayList<Integer>(temp));  
            return ;  
        }  
        temp.add(root.val);  
        if(root.left != null)  
        {     
            dfs(root.left, ans, temp, sum);  
            temp.remove(temp.size() - 1);  
        }  
        if(root.right != null)  
        {  
            dfs(root.right, ans, temp, sum);  
            temp.remove(temp.size() - 1);  
        }  
    }  
   
}
View Code

 

posted on 2015-06-17 23:14  gone~with~wind  阅读(433)  评论(0编辑  收藏  举报