blob: d496c2c5ea9e80dfc24c01f01882c0872baf5508 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
#include "leetcode.h"
class Solution {
public:
TreeNode *lowestCommonAncestor(TreeNode *root, TreeNode *p, TreeNode *q) {
int small = min(p->val, q->val), large = max(p->val, q->val);
while (root != nullptr) {
if (root->val > large)
root = root->left;
else if (root->val < small)
root = root->right;
else
return root;
}
return nullptr;
}
};
|