因为是从根节点开始的,如果root在pq之间,那root就是最近公共祖先。
#include<iostream>
#include<queue>
#include<vector>
#include<unordered_set>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode() : val(0), left(nullptr), right(nullptr) {}
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if (root == nullptr || root->left == nullptr || root->right == nullptr) return root;
if (root->val < p->val && root->val < q->val) return lowestCommonAncestor(root->right, p, q);
if (root->val > p->val && root->val > q->val) return lowestCommonAncestor(root->left, p, q);
return root;
}
};
void print(TreeNode* a) {
if (a != nullptr) {
cout << a->val;
print(a->left);
print(a->right);
}
}
int main() {
Solution test;
TreeNode* c = new TreeNode(1);
TreeNode* b = new TreeNode(3);
TreeNode* a = new TreeNode(2,c, b);
}