[leedcode 235] Lowest Common Ancestor of a Binary Search Tree
2015-08-08 18:34
232 查看
Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST.
According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes v and w as the lowest node in T that has both v and w as descendants (where we allow a node to be a descendant of itself).”
For example, the lowest common ancestor (LCA) of nodes
According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes v and w as the lowest node in T that has both v and w as descendants (where we allow a node to be a descendant of itself).”
_______6______ / \ ___2__ ___8__ / \ / \ 0 _4 7 9 / \ 3 5
For example, the lowest common ancestor (LCA) of nodes
2and
8is
6. Another example is LCA of nodes
2and
4is
2, since a node can be a descendant of itself according to the LCA definition.
/** * 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) { //借助二叉搜索树的性质,左子树小于根节点,右子树大于根节点的性质,对比p,q的值跟root值的关系,可得到下面的做法 if(root==null||p==null||q==null) return null; if(p==root||q==root) return root; int temp=root.val; if(temp>p.val&&temp>q.val){ return lowestCommonAncestor(root.left,p,q); }else if(temp<p.val&&temp<q.val) return lowestCommonAncestor(root.right,p,q); return root; } }
相关文章推荐
- JS - 鼠标经过边框旋转
- ajax提交下载文件
- springMVC的json交互
- iOS APP图标长按抖动效果的实现(CAAnimation)
- Java中普通代码块,构造代码块,静态代码块区别及代码示例
- 【CF 459D】 Pashmak and Parmida's problem
- 串行卧重建10:小设计,而不是大布局
- JS - 图片放大器
- Mac 常用软件下载
- Win10通用程序 UWP版HtmlAgilityPack UWP应用使用示例
- 智力题:1-28题
- java 静态代码块详解
- C#-WinForm登录窗体实现记住密码的功能(仿QQ实现)
- STP 标准生成树
- UIViewController - View Management(视图管理)
- 不应该学太多
- Android 属性动画(Property Animation) 完全解析 (下)
- (第七天)DOM练习一
- sendRedirect和getRequestDispatcher的一些区别
- 如何在面试中发现优秀程序员