返回二叉搜索树中任意两结点的最低的共同的祖先结点

/**
 * 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) {
        int bigOne   = 0;
        int smallOne = 0;
        
        if(p->val < q->val){
            bigOne   = q->val;
            smallOne = p->val;
        }
        else{
            bigOne   = p->val;
            smallOne = q->val;   
        }
        
        TreeNode *lowestCommonAncestor = root;
        while(true){
            if      (lowestCommonAncestor->val < smallOne){
                lowestCommonAncestor = lowestCommonAncestor->right;
            }
            else if (lowestCommonAncestor->val > bigOne){
                lowestCommonAncestor = lowestCommonAncestor->left;
            }
            else{
                return lowestCommonAncestor;
            }   
        }
    }
};

 

posted @ 2015-07-14 22:41  wu_overflow  阅读(134)  评论(0编辑  收藏  举报