leetcode - 112. Path Sum
2018-01-30 13:12
411 查看
Problem:
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
return true, as there exist a root-to-leaf path
sum is 22.
解释:给你一个整型的数sum,求解在树中是否有一条从根结点到叶节点的路径,满足所有val相加等于这个sum。
Solve:
调用递归进行遍历,思想是先判断当前结点是否满足sum-val=0?(题目给出的树都是正整数的情况)。不等的话再看左右结点,传入sum-val。
(时间复杂度O(n),AC-1ms)
后记:思想很明确,注意的地方在于路径需要是根结点到叶结点。中间结点即使找到了答案(sum-val=0)的情况也不能返回true。
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.
解释:给你一个整型的数sum,求解在树中是否有一条从根结点到叶节点的路径,满足所有val相加等于这个sum。
Solve:
调用递归进行遍历,思想是先判断当前结点是否满足sum-val=0?(题目给出的树都是正整数的情况)。不等的话再看左右结点,传入sum-val。
(时间复杂度O(n),AC-1ms)
public boolean hasPathSum(TreeNode root, int sum) { if(root==null){ return false; } if (sum-root.val==0&&root.right==null&&root.left==null){//叶节点的情况 return true; } if(hasPathSum(root.right,sum-root.val)){ return true; } if (hasPathSum(root.left, sum - root.val)) { return true; } return false; }
后记:思想很明确,注意的地方在于路径需要是根结点到叶结点。中间结点即使找到了答案(sum-val=0)的情况也不能返回true。
相关文章推荐
- 【一天一道LeetCode】#112. Path Sum
- LeetCode 112. Path Sum
- LeetCode 112. Path Sum
- [LeetCode]112. Path Sum
- [Leetcode] 112. Path Sum
- LeetCode-112. Path Sum
- [leetcode]112. Path Sum
- [LeetCode] 112. Path Sum
- LeetCode 112. Path Sum
- LeetCode 112. Path Sum
- leetcode 112. Path Sum
- [leetcode] @python 112. Path Sum
- LeetCode 112. Path Sum(路径和)
- 【LeetCode】 112. Path Sum
- LeetCode 112. Path Sum
- 【Leetcode】112. Path Sum
- LeetCode 112. Path Sum
- Leetcode 112. Path Sum
- 【LeetCode】112. Path Sum
- LeetCode 112. Path Sum