- 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; //分叉点
}
}
};