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

1.解题思路:
首先,这棵树一定需要遍历一遍,则可使用递归。
其次,需要用到list存储走过的节点,而在递归中,当前层的节点存储之后,如果退回到外面一层,则还需要删除这个节点(在递归方法中,list是传引用,改变对所有层而言都是成立的)
递归的终止条件是,搜索到某一层发现这个节点是个空(注意,这个时候依然需要给存储路径的list增加个值,随便一个值,因为退回到上一层是需要删除一个末尾节点的,否则就删除了前面一个尾节点了)
2.AC代码:
/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
     ArrayList<List<Integer>> rst = new ArrayList<List<Integer>>();

    public void search(TreeNode root, int curSum, int sum, LinkedList<Integer> tmpPath){
        if(root==null){
            tmpPath.addLast(-1);
            return;
        }
        tmpPath.addLast(root.val);
        if(curSum+root.val==sum && root.left==null && root.right==null){
            ArrayList<Integer> newRst = new ArrayList<Integer>();
            for(Integer integer:tmpPath){
                
                newRst.add(integer);
            }
           
            rst.add(newRst);
        }
        search(root.left, curSum+root.val, sum, tmpPath);
        tmpPath.pollLast();
        search(root.right, curSum+root.val, sum, tmpPath);
        tmpPath.pollLast();
    }
    public List<List<Integer>> pathSum(TreeNode root, int sum) {
        LinkedList<Integer> tmpPath = new LinkedList<Integer>();
        search(root, 0, sum, tmpPath);
        return rst;
    }
}



                
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值