112. 路径总和


112. 路径总和

难度简单 523
给你二叉树的根节点 root 和一个表示目标和的整数 targetSum ,判断该树中是否存在 根节点到叶子节点 的路径,这条路径上所有节点值相加等于目标和 targetSum
叶子节点 是指没有子节点的节点。

示例 1:

输入:root = [5,4,8,11,null,13,4,7,2,null,null,null,1], targetSum = 22
输出:true

广度优先

public boolean hasPathSum(TreeNode root, int sum) {
        if (root == null) {
            return false;
        }
        Queue<TreeNode> queNode = new LinkedList<TreeNode>();
        Queue<Integer> queVal = new LinkedList<Integer>();
        queNode.offer(root);
        queVal.offer(root.val);
        while (!queNode.isEmpty()) &#123;
            TreeNode now = queNode.poll();
            int temp = queVal.poll();
            if (now.left == null && now.right == null) &#123;
                if (temp == sum) &#123;
                    return true;
                &#125;
                continue;
            &#125;
            if (now.left != null) &#123;
                queNode.offer(now.left);
                queVal.offer(now.left.val + temp);
            &#125;
            if (now.right != null) &#123;
                queNode.offer(now.right);
                queVal.offer(now.right.val + temp);
            &#125;
        &#125;
        return false;
    &#125;

作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/path-sum/solution/lu-jing-zong-he-by-leetcode-solution/

递归

/**
 * Definition for a binary tree node.
 * public class TreeNode &#123;
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() &#123;&#125;
 *     TreeNode(int val) &#123; this.val = val; &#125;
 *     TreeNode(int val, TreeNode left, TreeNode right) &#123;
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     &#125;
 * &#125;
 */
class Solution &#123;
    public boolean hasPathSum(TreeNode root, int sum) &#123;
        if (root == null) &#123;
            return false;
        &#125;
        if (root.left == null && root.right == null) &#123;
            return sum == root.val;
        &#125;
        return hasPathSum(root.left, sum - root.val) || hasPathSum(root.right, sum - root.val);
    &#125;

// 作者:LeetCode-Solution
// 链接:https://leetcode-cn.com/problems/path-sum/solution/lu-jing-zong-he-by-leetcode-solution/
&#125;

文章作者:   future
版权声明:   本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 future !
 上一篇
226. 翻转二叉树 226. 翻转二叉树
226. 翻转二叉树难度简单 774翻转一棵二叉树。示例:输入:     4   /     2     7 / \   / 1   3 6   9输出:     4   /     7     2 / \   / 9   6 3   1
下一篇 
122. 买卖股票的最佳时机 II 122. 买卖股票的最佳时机 II
122. 买卖股票的最佳时机 II难度简单1108给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格。设计一个算法来计算你所能获取的最大利润。你可以尽可能地完成更多的交易(多次买卖一支股票)。注意:你不能同时参与多笔交易(你必
2021-03-01 future
  目录