leetcode--Lowest Common Ancestor of a Binary Search Tree
来源:互联网 发布:大数据目前发展情况 编辑:程序博客网 时间:2024/06/03 18:12
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).”
_______6______ / \ ___2__ ___8__ / \ / \ 0 _4 7 9 / \ 3 5
For example, the lowest common ancestor (LCA) of nodes 2
and 8
is 6
. Another example is LCA of nodes 2
and 4
is 2
, since a node can be a descendant of itself according to the LCA definition.
题意:对于一棵BST树,给出树上的两个节点,找出它们的最接近的共同祖先节点。
分类:二叉树
解法1:由于题目给出的是BST树,根据BST树的性质,对于某个节点,其左子树上的所有节点的值都比它小,右子树上的所有节点的值都比它大。
对于根节点root而言,如果p,q两个相比root,一大一小,说明root就是它们的LCA
如果都在比root小,说明它们的LCA在root的左子树上。如果都比root大,说明它们的LCA在root的右子树上。
如果它们有其中一个跟root相等,说明这个就是LCA
根据这个思路,我们很快写出代码:
解法2:解法2跟解法1的思路一样,但是精简了一下代码,除了在左右子树的情况,其余情况我们都可以返回root
原文链接http://blog.csdn.net/crazy__chen/article/details/47184681
- leetcode 235: Lowest Common Ancestor of a Binary Search Tree
- LeetCode 235. Lowest Common Ancestor of a Binary Search Tree
- leetcode: Lowest Common Ancestor of a Binary Search Tree
- [leetcode][dfs] Lowest Common Ancestor of a Binary Search Tree
- [leetcode] 235.Lowest Common Ancestor of a Binary Search Tree
- 【LeetCode】235 Lowest Common Ancestor of a Binary Search Tree
- [LeetCode]235.Lowest Common Ancestor of a Binary Search Tree
- leetcode 235 Lowest Common Ancestor of a Binary Search Tree
- [leetcode] Lowest Common Ancestor of a Binary Search Tree
- LeetCode Lowest Common Ancestor of a Binary Search Tree
- leetCode(38):Lowest Common Ancestor of a Binary Search Tree
- leetcode-235-Lowest Common Ancestor of a Binary Search Tree
- [LeetCode]Lowest Common Ancestor of a Binary Search Tree
- Leetcode: Lowest Common Ancestor of a Binary Search Tree
- leetcode[235]:Lowest Common Ancestor of a Binary Search Tree
- Lowest Common Ancestor of a Binary Search Tree-leetcode
- 【leetcode】Lowest Common Ancestor of a Binary Search Tree
- 【Leetcode】Lowest Common Ancestor of a Binary Search Tree
- GAN公式原理推到
- Spring(六)SSM(Spring3+Struts2+MyBatis+JDK1.7)
- js事件实现通过键盘移动图片
- Nginx配置参数详解
- HTML的TextArea标记跟随文本内容自动设置高度
- leetcode--Lowest Common Ancestor of a Binary Search Tree
- Java 详解 JVM 工作原理和流程
- 快速排序算法(java实现)
- Nginx
- 构建需求响应式亿级商品详情页
- jQuery 自定义弹窗插件
- uva 210 Concurrency Simulator
- 解决idea中创建activiti项目后如何生成bng图片及如何找到连线
- 计算机类学习总结