112 Path Sum
2015-12-15 21:37
274 查看
题目链接:https://leetcode.com/problems/path-sum/
题目:
解题思路:
这道题的考点就是前序遍历二叉树。
1. 每遇到一个结点就用 sum 减去该结点的值,把剩余的值传递到当前结点的子树中。
2. 直到遇到叶子结点,判断此时 sum 是否已被减为 0,若被减为 0,说明存在该路径,否则说明当前遍历到的这条路径不符合要求。
要注意判断根结点为空的情况!
代码实现:
题目:
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->2 which sum is 22.
解题思路:
这道题的考点就是前序遍历二叉树。
1. 每遇到一个结点就用 sum 减去该结点的值,把剩余的值传递到当前结点的子树中。
2. 直到遇到叶子结点,判断此时 sum 是否已被减为 0,若被减为 0,说明存在该路径,否则说明当前遍历到的这条路径不符合要求。
要注意判断根结点为空的情况!
代码实现:
/** * 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; return helper(root, sum); } boolean helper(TreeNode root, int sum) { if(root.left == null && root.right == null) { if(sum - root.val == 0) return true; else return false; } boolean left = false, right = false; if(root.left != null) left = helper(root.left, sum - root.val); if(root.right != null) right = helper(root.right, sum - root.val); if(!right && !left) return false; else return true; } }
114 / 114 test cases passed. Status: Accepted Runtime: 1 ms
相关文章推荐
- leetcode -- Search a 2D Matrix II -- 重点要理解
- Java NIO使用及原理分析(二)
- 扣丁学堂——收发短信
- jquery.validate校验+jquery.form提交,配合使用
- Java出现No enclosing instance of type E is accessible. Must qualify the allocation with an enclosing
- [Coursera]算法基础_Week9_考试_Q2
- IC分词和IK分词
- 第4天
- cutils-trace(18431): Error opening trace file: No such file or directory
- 前端小工具集合
- 一个非常简单的例子告诉你attachEvent和addEventListener的区别
- LeetCode 2 Add Two Numbers(链表操作)
- 电。视。电。影。。。网。。。站
- 递归读取heritrix 爬下来的目录文件
- 数组和指针
- LeetCode 213:House Robber II
- 进击的KFC:UI(14)集合视图UICollectionView
- [HDU 1427]速度计算24点(DFS暴力搜索)
- 家庭作业汇总
- This Is The Rule That Follow