My cpp solution


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

Log in to reply
 

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