[LeetCode] Path Sum && Path Sum II

Path Sum: https://oj.leetcode.com/problems/path-sum/

要求解从根到叶子节点的路径的和,首先要从根节点遍历到叶子节点,所以我们需要对树进行深度优先遍历,采用递归的方法解决;每遍历到一个节点,我们将原来的sum减去该节点的值,假如减去某叶子节点的值后,剩余为0,则说明从根节点到该叶子节点的和为原来的sum

代码如下:

public class Solution {
    public boolean hasPathSum(TreeNode root, int sum) {
        if(root == null)
            return false;
        if(sum - root.val == 0 && root.left == null && root.right == null)
            return true;
        return hasPathSum(root.left, sum-root.val) || hasPathSum(root.right, sum-root.val);
    }
}

Path Sum II: https://oj.leetcode.com/problems/path-sum-ii/

这个问题需要找到所有的解,所以我们可以借助辅助存储来存储从根节点到当前节点的路径,因为是深度优先遍历,所以我们采用栈来存储路径上的节点;

代码如下:

public class Solution {
    public List<List<Integer>> pathSum(TreeNode root, int sum) {
        List<List<Integer>> result = new ArrayList<List<Integer>>();
        if(root == null)
            return result;
        Stack<Integer> stack = new Stack<Integer>();
        path(result, stack, root, sum);
        return result;
    }
    public void path(List<List<Integer>> result, Stack<Integer> stack, TreeNode root, int sum){
        if(root == null)
            return;
        stack.push(root.val);
        if(root.left == null && root.right == null){
            if(sum - root.val == 0)
                result.add(new ArrayList<Integer>(stack));
            stack.pop();
            return;
        }
        path(result, stack, root.left, sum-root.val);
        path(result, stack, root.right, sum-root.val);
        stack.pop();
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值