C++ 26ms solution, iterative and recursive


  • 0
    Y

    Recursive solution.

    class Solution {
    public:
        TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
            if (!root || !p || !q) return nullptr;
            
            // make sure p is smaller than q
            if (p->val > q->val) return lowestCommonAncestor(root, q, p);
            
            if (root->val < p->val) {
                return lowestCommonAncestor(root->right, p, q);
            } else if (root->val > q->val) {
                return lowestCommonAncestor(root->left, p, q);
            } else {
                return root;
            }
        }
    };
    

    Iterative solution

    class Solution {
    public:
        TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
            if (!root || !p || !q) return nullptr;
            
            // make sure p is smaller than q
            if (p->val > q->val) return lowestCommonAncestor(root, q, p);
            
            while (root) {
                if (root->val < p->val) {
                    root = root->right;
                } else if (root->val > q->val) {
                    root = root->left;
                } else {
                    return root;
                }
            }
            
            return root;
        }
    };
    

Log in to reply
 

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