Java Simple Solution Beat 97%


  • 0
    X

    The idea is simple: the value of parent must be between p and q, try to find it. If cant, the parent does not exist.

    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
            
            if (root == null) return null;
            if (p == null) return q;
            if (q == null) return p;
            
            TreeNode v = p.val < q.val ? p : q;
            TreeNode w = p.val > q.val ? p : q;
            
            TreeNode curr = root;
            while (curr != null && (curr.val > w.val || curr.val < v.val)) {
                if (curr.val < v.val) curr = curr.right;
                if (curr.val > w.val) curr = curr.left;
            }
            
            return curr;
        }
    

Log in to reply
 

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