来源
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/lowest-common-ancestor-of-a-binary-search-tree/
描述
给定一个二叉搜索树, 找到该树中两个指定节点的最近公共祖先。
说明:
- 所有节点的值都是唯一的。
-
题解
递归
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
int parentVal = root.val;
int pVal = p.val;
int qVal = q.val;
if (pVal > parentVal && qVal > parentVal) {
return lowestCommonAncestor(root.right, p, q);
} else if (pVal < parentVal && qVal < parentVal) {
return lowestCommonAncestor(root.left, p, q);
} else {
return root;
}
}
}
复杂度分析
时间复杂度:
,其中
为BST中节点的个数,在最坏的情况下我们可能需要遍历BST中所有的节点。
- 空间复杂度:
,所需开辟的额外空间主要是递归栈产生的,之所以是
是因为BST的高度为
。
迭代
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
int pVal = p.val;
int qVal = q.val;
TreeNode node = root;
while (node != null) {
int parentVal = node.val;
if (pVal > parentVal && qVal > parentVal) {
node = node.right;
} else if (pVal < parentVal && qVal < parentVal) {
node = node.left;
} else {
return node;
}
}
return null;
}
}
复杂度分析
- 时间复杂度:
,其中
为BST中节点的个数,在最坏的情况下我们可能需要遍历BST中所有的节点。
- 空间复杂度: