Lowest Common Ancestor of a Binary Search Tree
2015-08-30 11:20
204 查看
题目:
Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST.
Analysis
This problem can be solved by using BST property, i.e., left < parent < right for each node. There are 3 cases to handle.
reference:http://www.programcreek.com/2014/07/leetcode-lowest-common-ancestor-of-a-binary-search-tree-java/
Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST.
Analysis
This problem can be solved by using BST property, i.e., left < parent < right for each node. There are 3 cases to handle.
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { TreeNode m = root; if(m.val>p.val&&m.val<q.val) return m; if(m.val>p.val&&m.val>q.val) { return lowestCommonAncestor(root.left,p,q); } if(m.val<p.val&&m.val<q.val) { return lowestCommonAncestor(root.right,p,q); } return root; }
reference:http://www.programcreek.com/2014/07/leetcode-lowest-common-ancestor-of-a-binary-search-tree-java/
相关文章推荐
- Mex 文件
- Codeforces Round #318 (Div. 2) A、B、C
- FCKeditor文件上传配置
- html5--如何用canvas画一个钟
- 程序之美
- sed常用用法技巧举例
- java常用集合类详解
- 对大对象进行排序的算法
- poj 3903 Stock Exchange 最长上升子序列
- python 排序归纳
- Java功底篇系列-04-基本类型/包装类型/Collections/Arrays
- Bear and Elections
- UI设计规范
- 爬虫论坛分享
- 红黑树
- Spring笔记⑥--整合struts2
- HTTP详解1-工作原理
- vmware workstation进入BIOS
- 指向函数的指针和返回值是指针类型的函数
- servlet监听器的学习