leetcode 112.路径总和 Java

这篇博客介绍了如何解决LeetCode上的‘路径总和’问题,通过深度优先搜索(DFS)和广度优先搜索(BFS)两种方法在二叉树中寻找从根节点到叶子节点且节点值之和等于给定目标和的路径。示例代码展示了如何实现这两种方法,并给出了判断条件。
摘要由CSDN通过智能技术生成

题目链接

https://leetcode-cn.com/problems/path-sum/

描述

给定一个二叉树和一个目标和,判断该树中是否存在根节点到叶子节点的路径,这条路径上所有节点值相加等于目标和。

说明: 叶子节点是指没有子节点的节点。

示例

给定如下二叉树,以及目标和 sum = 225
             / \
            4   8
           /   / \
          11  13  4
         /  \      \
        7    2      1
返回 true, 因为存在目标和为 22 的根节点到叶子节点的路径 5->4->11->2

初始代码模板

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public boolean hasPathSum(TreeNode root, int sum) {

    }
}

代码

dfs

如果当前节点是叶子节点,就判断值是否和给定的sum相等,不相等则说明这条路径不满足要求。通向各个叶子节点的路径有一条即可返回true

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public boolean hasPathSum(TreeNode root, int sum) {
        if (root == null) {
            return false;
        }

        if (root.left == null && root.right == null) {
            return root.val == sum;
        }

        return hasPathSum(root.left, sum - root.val) || hasPathSum(root.right, sum - root.val);
    }
}

BFS

这里也可以自定义一种类型,来保存节点和当前的和。
如果数据范围过大也要注意变量保存的范围,一下代码仅可参考。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public boolean hasPathSum(TreeNode root, int sum) {
        if (root == null) {
            return false;
        }

        Queue<TreeNode> nodeQueue = new LinkedList<>();
        Queue<Integer> valQueue = new LinkedList<>();
        nodeQueue.offer(root);
        valQueue.offer(root.val);

        while (!nodeQueue.isEmpty()) {
            for (int i = nodeQueue.size(); i > 0; i--) {
                TreeNode node = nodeQueue.poll();
                int curSum = valQueue.poll();

                if (node.left == null && node.right == null && curSum == sum) {
                    return true;
                }

                if (node.left != null) {
                    nodeQueue.offer(node.left);
                    valQueue.offer(curSum + node.left.val);
                }

                if (node.right != null) {
                    nodeQueue.offer(node.right);
                    valQueue.offer(curSum + node.right.val);
                }
            }
        }

        return false;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值