LeetCode Lowest Common Ancestor of a Binary Tree
2015-09-05 05:11
309 查看
原题链接在这里:https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/
是Lowest Common Ancestor of a Binary Search Tree的进阶题目。无法比较大小,但是可以看p,q是不是在root的两边,若在两边,则返回root.
若都在一边,就在那一边继续。
Note: 1. 若有root == p || root == q时,需比较原来的点而不单单是val, 这里可以有重复的值,在能比较整体点时就不比较val.
2. 递归终止条件这里有两个,一个是root == null, 一个是root等于p或者q, 这两个终止条件缺一不可。
AC Java:
是Lowest Common Ancestor of a Binary Search Tree的进阶题目。无法比较大小,但是可以看p,q是不是在root的两边,若在两边,则返回root.
若都在一边,就在那一边继续。
Note: 1. 若有root == p || root == q时,需比较原来的点而不单单是val, 这里可以有重复的值,在能比较整体点时就不比较val.
2. 递归终止条件这里有两个,一个是root == null, 一个是root等于p或者q, 这两个终止条件缺一不可。
AC Java:
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { if(root == null){ return root; } if(root == p || root == q){ return root; } TreeNode left = lowestCommonAncestor(root.left,p,q); TreeNode right = lowestCommonAncestor(root.right,p,q); if(left != null && right != null){ return root; }else if(left != null){ return left; }else if(right != null){ return right; }else{ return null; } } }
相关文章推荐
- LeetCode Lowest Common Ancestor of a Binary Tree
- 转载几个网站
- Perl Connect to Database without password as sysdba
- Bequeath Connection and SYS Logon
- Tomcat源码阅读系列(八)设计模式
- LeetCode Lowest Common Ancestor of a Binary Search Tree
- 最大连续区间和(非环) -dp/分治
- LeetCode Lowest Common Ancestor of a Binary Search Tree
- js学习资料
- git 解决The current branch is not configured for pull No value for key branch.master.merge found in co
- 一个项目思路(0):DButil的抽象写法
- [LeetCode]Kth Smallest Element in a BST
- 一个项目思路(1):用反射机制写的函数,使2个javabean相同属性一次性导入
- Linux系统启动流程与grup
- 【小熊刷题】power of two, pow(x, n) <Leetcode 231, 50 Java>
- SSH-jar包相应作用
- 如何为编程爱好者设计一款好玩的智能硬件(一)——即插即用、积木化、功能重组的智能硬件模块构想
- servlet&jsp jar包 下载
- VS2012单元测试
- php 与jquery 选中select