树类型的题目的总结 leetcode 112, 235
2017-08-12 09:57
302 查看
首先我们知道,树是一种递归的结构,所以在解决树的问题上,我们经常可以使用递归的求解方式求解,思路非常清晰,代码也非常简洁。掌握了基本的思路之后,再碰到类似的题目之后,我们可以使用相类似的思路去想解决的办法,然后代码实现思路。
leetcode 112
这事一道easy题,想到了递归的思路之后就顺理成章。首先先写当前的返回条件,然后在写返回true时候的情况。
Leetcode 235
这道题目仍然可以使用递归的方式去求解,在递归求解的过程中,我们要注意题目中binary search tree,可以利用binary search tree的特点作为返回的判断依据。
如果p和q分别在两个不同的子树上,那么直接返回root, 如果p和q在同一棵子树上,那么就递归求解。直到返回答案。
leetcode 112
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { public boolean hasPathSum(TreeNode root, int sum) { if(root == null) return false; if(root.left == null && root.right == null && sum - root.val == 0 ) return true; return hasPathSum(root.left, sum - root.val) || hasPathSum(root.right, sum - root.val); } }
这事一道easy题,想到了递归的思路之后就顺理成章。首先先写当前的返回条件,然后在写返回true时候的情况。
Leetcode 235
这道题目仍然可以使用递归的方式去求解,在递归求解的过程中,我们要注意题目中binary search tree,可以利用binary search tree的特点作为返回的判断依据。
如果p和q分别在两个不同的子树上,那么直接返回root, 如果p和q在同一棵子树上,那么就递归求解。直到返回答案。
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { TreeNode result = root; if((p.val > root.val && q.val < root.val) || (p.val < root.val && q.val > root.val)) return root; if(p.val > root.val && q.val > root.val) result = lowestCommonAncestor(root.right, p,q); if(p.val < root.val && q.val < root.val) result = lowestCommonAncestor(root.left, p,q); return result; } }
相关文章推荐
- [leetcode] String类型题目总结
- leetcode 题目类型分类总结
- [Leetcode]database 相关题目的总结
- leetcode题目总结(转)
- leetcode题目总结<2>
- leetcode做题总结,题目Spiral Matrix I/II 2012/03/24
- LeetCode 题目总结/分类
- leetcode做题总结,题目Container With Most Water------ 2012/01/08
- [LeetCode刷题笔记]Math数学类型题目(三)特殊的数字结构
- leetcode刷题,总结,记录,备忘235
- leetcode题目总结<1>
- leetcode做题总结,题目Search a 2D MatrixI/II 2012/04/06
- leetcode做题总结,题目Sort List 2013/11/16
- leetcode做题总结,题目Reverse Nodes in k-Group 2012/02/15
- 动态规划“数塔”类型题目总结
- Leetcode 题目类型分布
- leetcode题目分类/总结
- leetcode做题总结,题目Plus One 2012/04/02
- LeetCode-二分查找面试题目总结
- leetcode做题总结,题目Copy List with Random Pointer 2013/10/03