LCA in BST
2015-08-09 17:22
323 查看
题目:Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST.
思路:
两节点 p , q , 分多中情况考虑, 因为是BST, 如果 p < root , q > root ==> LCA = root
如果 p = Max(p , q ) < root == 》 LCA = LCA (root.left , p ,q) // 在左子树中求LCA
p = Max(p , q ) > root 同理
思路:
两节点 p , q , 分多中情况考虑, 因为是BST, 如果 p < root , q > root ==> LCA = root
如果 p = Max(p , q ) < root == 》 LCA = LCA (root.left , p ,q) // 在左子树中求LCA
p = Max(p , q ) > root 同理
[code]public class Solution { public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { int min = Math.min(p.val , q.val); int max = Math.max(p.val , q.val); while(root != null) { if(root.val > max) { return lowestCommonAncestor(root.left , p , q); } else if(root.val < max){ if(root.val >= min) return root; return lowestCommonAncestor(root.right, p , q); } else if(root.val == max) return root; } return null; } }
相关文章推荐
- java单链表常用操作
- hdu 5317 RGCDQ(预处理)
- 类的锁
- 计数排序
- Myeclipse8.6 快速搭建ssh(JPA)开发环境 并自动生成dao ,model
- 在onResume()中调用getIntent()得不到Extra的问题
- Java之旅(3)——EJB(初始)
- 在onResume()中调用getIntent()得不到Extra的问题
- Hibernate性能优化技巧
- Linux - 主机的细部权限规划:ACL 的使用
- uva10791 Minimum Sum LCM(唯一分解定理)
- Linux - 主机的细部权限规划:ACL 的使用
- java.lang包下Number的简介
- [2015hdu多校联赛补题]hdu5299 Circles Game
- java编写一个分页类
- PHP运算符===和==的区别
- Objective-C学习笔记_NSDate、NSDateFormatter
- Android Api Demos登顶之路(二十五)Action Bar Mechanics
- Leetcode53 Maximum Subarray
- LeetCode#5 Longest Palindromic Substring