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

/**
 * 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;
            }   
        }
    }
};
原文地址:https://www.cnblogs.com/wuOverflow/p/4646792.html