235. Lowest Common Ancestor of a Binary Search Tree
Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST.
According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes v and w as the lowest node in T that has both v and w as descendants (where we allow a node to be a descendant of itself).”
解题思路:充分利用二叉搜索树的性质,即左子树的节点值小于根节点的值,右子树的节点值大于根节点值,然后进行递归搜索,直至p和q分居根节点两边。
/**
* 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||p==NULL||q==NULL)
return NULL;
int douct=(p->val-root->val)*(q->val-root->val);
int sum=(p->val-root->val)+(q->val-root->val);
if(douct<=0)
return root;
if(sum<0)
return lowestCommonAncestor(root->left,p,q);
if(sum>0)
return lowestCommonAncestor(root->right,p,q);
}
};