给定一个二叉搜索树, 找到该树中两个指定节点的最近公共祖先。
这道题一定要了解二叉搜索树的性质,右边比左边大。
python:
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def lowestCommonAncestor(self, root, p, q):
"""
:type root: TreeNode
:type p: TreeNode
:type q: TreeNode
:rtype: TreeNode
"""
if root == None:
return None
if (p.val <= root.val and root.val <= q.val) or (q.val <= root.val and root.val <= p.val):
return root
if (p.val < root.val) and (q.val < root.val):
return self.lowestCommonAncestor(root.left,p,q)
if (p.val > root.val) and (q.val > root.val):
return self.lowestCommonAncestor(root.right,p,q)
C++:
/**
* 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 == NULL) return NULL;
if((root->val>=p->val&&root->val<=q->val) || (root->val>=q->val&&root->val<=p->val)) return root;
if(root->val>p->val&&root->val>q->val) return lowestCommonAncestor(root->left,p,q);
if(root->val<p->val&&root->val<q->val) return lowestCommonAncestor(root->right,p,q);
return NULL;
}
};