LeetCode 112. Path Sum (二叉树路径之和)
2017-07-04 06:17
411 查看
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.
For 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->2which sum is 22.
题目标签:Tree
这道题目给了我们一个二叉树和一个sum, 让我们判断这个二叉树是否有至少一条path 的之和是等于sum的。利用preOrder 来遍历树,每次用sum 减去当前点的值,每当遇到一个leaf node 的时候检查sum 是不是等于0, 返回ture 和false。利用 || 来return 所有的boolean 值, 至少有过一个true,一个path之和等于sum, 总的boolean 就是true。
Java Solution:
Runtime beats 13.93%
完成日期:07/03/2017
关键词:Tree
关键点:当是leaf node 的时候检查sum;利用 || return两个children的返回值
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public boolean hasPathSum(TreeNode root, int sum) { if(root == null) return false; sum -= root.val; if(root.left == null && root.right == null) { if(sum == 0) return true; else return false; } return hasPathSum(root.left, sum) || hasPathSum(root.right, sum); } }
参考资料:
http://www.cnblogs.com/springfor/p/3879825.html
LeetCode 算法题目列表 - LeetCode Algorithms Questions List
相关文章推荐
- Binary Tree Maximum Path Sum (二叉树路径和的最大值) 【leetcode】
- [LeetCode] Path Sum IV 二叉树的路径和之四
- LeetCode-Binary Tree Maximum Path Sum-二叉树最大路径和-DFS
- LeetCode(124) Binary Tree Maximum Path Sum 二叉树的最大路径和 (如何递归?)
- LeetCode | Binary Tree Maximum Path Sum(二叉树的路径最大值)
- Leetcode 124 Binary Tree Maximum Path Sum 二叉树最大路径和
- LeetCode (12) Path Sum (二叉树路径和判断)
- Leetcode:112. Path Sum (求Tree中是否存在路径的和等于给定值)
- [LeetCode 124] - 二叉树最大路径和(Binary Tree Maximum Path Sum)
- LeetCode 二叉树路径问题 Path SUM(①②③)总结
- leetcode 112. Path Sum(C语言,二叉树,递归思想)28
- [Leetcode] Binary tree maximum path sum求二叉树最大路径和
- [LeetCode] Path Sum II 二叉树路径之和之二
- 【leetcode 二叉树路径和】Path Sum 和 Path Sum II
- LeetCode(Binary Tree Maximum Path Sum) 在二叉树中找出一条和最大的路径
- [LeetCode]437. Path Sum III(求二叉树中路径和等于sum的数量)
- [LeetCode] Path Sum III 二叉树的路径和之三
- leetCode 112.Path Sum (路径和) 解题思路和方法
- [LeetCode] Binary Tree Maximum Path Sum 求二叉树的最大路径和
- LeetCode 437. Path Sum III 题解 和固定的二叉树路径数目