0%

235. Lowest Common Ancestor of a Binary Search Tree

O(h)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if (!root) return nullptr;
if (!p || !q) return root;
auto [s, l] = minmax(p->val, q->val);
if (s <= root->val && root->val <= l) return root; // 注意等于的case,说明p和q一个是另一个的父节点
if (root->val < s) return lowestCommonAncestor(root->right, p, q);
if (l < root->val) return lowestCommonAncestor(root->left, p, q);
return nullptr;
}
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
auto [lo, hi] = minmax(p->val, q->val);
if (lo <= root->val && root->val <= hi) return root;
return hi < root->val ? lowestCommonAncestor(root->left, p, q) : lowestCommonAncestor(root->right, p, q);
}
};