【ACM从零开始】LeetCode OJ-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.

题目大意:给出两个二叉树的结点,寻找这两个结点最近的那个公共父结点(LCA)。比如如图,结点“2”和“8”的LCA是6,结点“2”和“4”的LCA是2。

解题思路:

这题要结合二叉树的规律,即左孩子小于根结点小于右孩子。所以当给出的结点p和q,如果p,q<root,则LCA必在左子树;如果p<root<q,则LCA为root;如果root<p,q,则LCA必在右子树。

结合三种情况,首先求出结点p和结点q中较大的那个,与root进行比较,如果比root小,遍历左子树;如果比root大,遍历右子树;都不满足,返回root。

AC代码:

class Solution {
public:
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
        if(!root || !p || !q)return NULL;
        if(p->val < root->val && q->val < root->val)
            lowestCommonAncestor(root->left,p,q);
        else if(p->val > root->val && q->val > root->val)
            lowestCommonAncestor(root->right,p,q);
        else
            return root;
    }
};

posted @ 2015-10-11 14:50  Shvier  阅读(151)  评论(0编辑  收藏  举报