C++ simple solution, 4lines, 34ms, No extra space


  • 1
    J

    use (root->val - p->val)*(root->val - q->val) to determine if q and q are at the same side or not. If <0, p,q are in the opposite side or one of them at the root, return the root. if >0, p,q are at the different side, move the pointer to its left or right depending on the p or q's value compared to root's value.

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

Log in to reply
 

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