leetcode 112.路径总和 Java

    科技2022-08-16  101

    路径总和

    题目链接描述示例初始代码模板代码dfsBFS

    题目链接

    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; } }
    Processed: 0.021, SQL: 9