(easy)LeetCode 235.Lowest Common Ancestor of a Binary Search Tree
2015-07-31 19:49
375 查看
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
思想:如果如果p,q 比root小, 则LCA必定在左子树, 如果p,q比root大, 则LCA必定在右子树. 如果一大一小, 则root即为LCA.
代码如下:
运行结果:
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.
思想:如果如果p,q 比root小, 则LCA必定在左子树, 如果p,q比root大, 则LCA必定在右子树. 如果一大一小, 则root即为LCA.
代码如下:
/** * 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.val>=p.val && root.val<=q.val || root.val<=p.val && root.val>=q.val) return root; else if(root.val>=p.val && root.val>=q.val) return lowestCommonAncestor(root.left,p,q); else return lowestCommonAncestor(root.right,p,q); } }
运行结果:
相关文章推荐
- UIScrollView的属性总结
- 浅析notifyDataSetChanged内部工作流程
- 秒杀多线程第五篇 经典线程同步 关键段CS
- Android学习笔记之事件分发机制(二)
- JUnit4---eclipse实现java代码单元测试
- 使用信鸽推送时打开指定页面的同时获取相关参数
- HDU 4297 One and One Story 分类讨论, LCA 2012年成都网络赛J题
- HTML 标签列表(4)
- Sql 新建表并插入1000随机数
- 我是如何开始去了解Python函数式编程--Python函数式编程初涉
- hdu 5318 2015多校对抗赛三
- [UVA120]Stacks of Flapjacks[STL][构造]
- 《汇编语言》第二版 王爽著 第七章 更灵活的定位内存地址的方法 要点
- 扩展欧几里德 POJ1061
- .NET框架 三种预定义特性的介绍
- ACM比较1和0的个数
- java多线程基础部分探究
- left join on 和where条件的放置
- java.多线程
- 我是如何开始去了解Python函数式编程--Python函数式编程初涉