Two solutions in C++,recursion and iteration


  • 1
    V

    Solution (1):

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

    Solution (2):

    class Solution {
    public:
        TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
            if (root == NULL || root == p || root == q) return root;
            if (p == NULL || q == NULL) return NULL;
            
            int minv = p->val;
            int maxv = q->val;
            if (minv > maxv)
                maxv = minv, minv = q->val;
            
            while (1)
            {
                if (root->val > maxv)
                    root = root->left;
                else if (root->val < minv)
                    root = root->right;
                else 
                    return root;
            }
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.