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

 

path sum 是这个的基础,

path sum I是问存不存在这样一条路径,使得路径和为sum。使用递归。深度优先遍历的递归求法,见树的广度优先遍历和深度优先遍历(递归非递归、Java实现)
这题是要让求出这样的路径,也是同样地思路,使用递归,因为要添加到list中,所以每遍历一个就要往list中添加,直到叶子节点,判断是否等于sum,当等于,表明该路径符合,将list加到结果集中,同时别忘了,要删除叶子节点,再返回,进行下一个叶子判断。
如果不满足要求或者不是叶子节点,则将该节点加到list中,并继续遍历左右子树,遍历完了,也要删除该节点,返回上一层。

 

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public List<List<Integer>> pathSum(TreeNode root, int sum) {
        List<List<Integer>> res=new ArrayList<List<Integer>>();
        if(root==null) return res;
        helper(root,sum,res,new ArrayList<Integer>());
        return res;
    }
    public void helper(TreeNode root,int sum,List<List<Integer>> res,List<Integer> list){
        if(root==null) return;   //使用这个,就不用再讨论左右子树谁为空了
        
        if(root.left==null&&root.right==null&&root.val==sum){
            list.add(root.val);
            res.add(new ArrayList<Integer>(list));
            list.remove(list.size()-1);   //要将其删除再返回上一层
            return ;
        }else{
            list.add(root.val);
            helper(root.left,sum-root.val,res,list);
            helper(root.right,sum-root.val,res,list);
            list.remove(list.size()-1);   //将其删除再返回上一层。
        }
    }
}

 

posted on 2018-01-09 20:34  夜的第八章  阅读(141)  评论(0)    收藏  举报

导航