[LeetCode] 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).”

        _______6______
       /              \
    ___2__          ___8__
   /      \        /      \
   0      _4       7       9
         /  \
         3   5

For example, the lowest common ancestor (LCA) of nodes 2 and 8 is 6. Another example is LCA of nodes 2 and 4 is 2, since a node can be a descendant of itself according to the LCA definition.

 

分析:二叉搜索树是排序过的,位于左子树的节点都比父节点小,而位于右子树的节点都比父节点大,我们只需要从树的根节点开始和两个输入的节点比较。如果当前节点的值比两个节点的值都大,那么最低公共祖先一定是在当前节点的左子树中,于是下一步遍历当前节点的左子树。如果当前节点的值比两个节点的值都小,那么最低公共祖先一定在当前节点的右子树中,于是下一步遍历当前节点的右子树。这样在树中从上到下找到的第一个在两个输入节点的值之间的节点,就是最低的公共祖先。

/**
 * 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->val < p->val && root->val < q->val) {
            return lowestCommonAncestor(root->right, p, q);
        } else if (root->val > p->val && root->val > q->val) {
             return lowestCommonAncestor(root->left, p, q);
        } else {
            return root;
        }
 
    }
};

 

posted @ 2015-09-02 16:46  vincently  阅读(189)  评论(0编辑  收藏  举报