235. Lowest Common Ancestor of a Binary Search Tree
来源:互联网 发布:妙味课堂js课后练习 编辑:程序博客网 时间:2024/06/03 16:59
- Total Accepted: 129842
- Total Submissions: 337481
- Difficulty: Easy
- Contributor: LeetCode
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.
Subscribe to see which companies asked this question.
这一题的意思是要我们寻找BST两个节点p、q的最小共同根
我想到的第一个方法是,先保存从根到p节点上的所有点,包括p自己,保存在一个数组v中。然后从根节点开始寻找q,在寻找q的过程中,经过的最后一个包含在v中的节点就是他们的共同节点。这样的方法时间复杂度为O(logm*n),空间复杂度为O(logm)。于是我开始寻找更好的方法,尽量不需要额外空间。经过思考后,想出了一个主意。可以先从根节点开始同时寻找p和q,一定有一段路径是它们共同的。只要沿着这条路走,当它们到达某个节点时总会“分叉”开。这个"分叉路口”节点就是它们共同最小根节点。
代码如下:
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
TreeNode* cur = root;
while (true) {
if (p -> val < cur -> val && q -> val < cur -> val) //共同路径
cur = cur -> left;
else if (p -> val > cur -> val && q -> val > cur -> val) //共同路径
cur = cur -> right;
else return cur; //分叉点
}
}
};
- 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
- 235.Lowest Common Ancestor of a Binary Search Tree
- 235. Lowest Common Ancestor of a Binary Search Tree
- 235. Lowest Common Ancestor of a Binary Search Tree
- 235. Lowest Common Ancestor of a Binary Search Tree
- 【LeetCode】235. Lowest Common Ancestor of a Binary Search Tree
- 235. Lowest Common Ancestor of a Binary Search Tree LeetCode
- 235. Lowest Common Ancestor of a Binary Search Tree
- 235. Lowest Common Ancestor of a Binary Search Tree
- 235. Lowest Common Ancestor of a Binary Search Tree
- LeetCode 235. Lowest Common Ancestor of a Binary Search Tree
- 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] 235. Lowest Common Ancestor of a Binary Search Tree
- Android Studio如何查看Gradle版本
- 经典计算机书籍-自制系列
- java字符与Unicode的转换
- 第八周——135. Candy
- 使用JAVA代码发送MQ消息
- 235. Lowest Common Ancestor of a Binary Search Tree
- JS中几种常见的集合
- 2017.4.16 关于加密
- ArrayList的源码简单分析分析
- 安卓跳转与参数传递
- 《高效能人士的7个习惯》笔记
- Jquery实现点击切换单元格改变背景色
- SpringMVC从Controller跳转到另一个Controller
- 经典计算机图书-图解系列