【LeetCode】#112路径总和(Path Sum)
2018-12-15 20:16
120 查看
【LeetCode】#112路径总和(Path Sum)
题目描述
给定一个二叉树和一个目标和,判断该树中是否存在根节点到叶子节点的路径,这条路径上所有节点值相加等于目标和。
说明: 叶子节点是指没有子节点的节点。
示例
给定如下二叉树,以及目标和 sum = 22,
5
/
4 8
/ /
11 13 4
/ \
7 2 1
返回 true, 因为存在目标和为 22 的根节点到叶子节点的路径 5->4->11->2。
Description
Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.
Note: A leaf is a node with no children.
Example
Given the below binary tree and sum = 22,
5
/
4 8
/ /
11 13 4
/ \
7 2 1
return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22.
解法
class Solution { public boolean hasPathSum(TreeNode root, int sum) { if(root==null) return false; if(root.left==null && root.right==null) return sum-root.val==0; return hasPathSum(root.left, sum-root.val) || hasPathSum(root.right, sum-root.val); } }阅读更多
相关文章推荐
- 【LeetCode】#113路径总和II(Path Sum II)
- [Leetcode-64]Minimum Path Sum 二维数组路径最小和
- leetcode解题之62&63. Unique Paths ||64. Minimum Path Sum java版(路径(最短)可达)
- 【leetcode 二叉树路径和】Path Sum 和 Path Sum II
- LeetCode | Minimum Path Sum(最小路径和)
- LeetCode(Binary Tree Maximum Path Sum) 在二叉树中找出一条和最大的路径
- Binary Tree Maximum Path Sum (二叉树路径和的最大值) 【leetcode】
- [LeetCode] Binary Tree Maximum Path Sum(最大路径和)
- [Leetcode] Path Sum II路径和
- LeetCode:Minimum Path Sum(网格最大路径和)
- leetcode之二叉树类之路径和系列-----112/113/124/257/437 path sum(牵扯附加OJ572和OJ100, 子树和子拓扑)
- LeetCode 二叉树路径问题 Path SUM(①②③)总结
- 【LeetCode-面试算法经典-Java实现】【112-Path Sum(路径和)】
- LeetCode Path Sum 路径和
- [LeetCode] Path Sum III 二叉树的路径和之三
- [LeetCode 124] - 二叉树最大路径和(Binary Tree Maximum Path Sum)
- LeetCode-112-Path Sum(路径和)
- LeetCode Path Sum II路径和II
- [LeetCode] Binary Tree Maximum Path Sum 求二叉树的最大路径和
- leetcode64-Minimum Path Sum(最小路径和)