思路:
二叉搜索樹,對於二叉搜索樹中的每一個節點,其左子節點的值小於當前節點的值,右子節點的值大於當前節點的值。
遞歸尋找相應節點。
如果兩個節點不分佈在以一個節點爲根的同一側,則此節點爲祖先。
那麼我們可以在兩個節點在同一側時,根據二叉搜索樹的特性進行縮小樹的範圍。
答案:
/**
* 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 == nullptr) return nullptr;
if(p->val < root->val && q->val < root->val)
return lowestCommonAncestor(root->left, p, q);
if(p->val > root->val && q->val > root->val)
return lowestCommonAncestor(root->right,p,q);
return root;
}
};