LeetCode#113. Path Sum II

  • 题目:找出所有从根节点到叶子节点的路径,使得路径节点值之和等于sum
  • 难度:Medium
  • 思路:先序遍历二叉树,将当前结果加入结果集tmpList中,遍历的过程中,不断更新sum,直到sum等于node.val
  • 代码:
public class Solution {
    public List<List<Integer>> pathSum(TreeNode root, int sum) {
        List<List<Integer>> result = new ArrayList<>();
        if(root == null){
            return result;
        }
        helper(result, new ArrayList<>(), sum, root);
        return result;
    }
    public void helper(List<List<Integer>> list, List<Integer> tmp, int sum, TreeNode node){
        tmp.add(node.val);

        if(node.val == sum  && node.left == null && node.right == null){
            list.add(tmp);
            return;
        }

        if(node.left != null){
            helper(list, new ArrayList<>(tmp), sum-node.val, node.left);
        }
        if(node.right != null){
            helper(list, new ArrayList<>(tmp), sum-node.val, node.right);
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值