11ms java solution, 3 lines


  • 18
    Y
     public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if(root.val<Math.min(p.val,q.val)) return lowestCommonAncestor(root.right,p,q);
        if(root.val>Math.max(p.val,q.val)) return lowestCommonAncestor(root.left,p,q);
        return root;
    }

  • 2
    S

    this solution is not complete. It assumes root, p, q are not null and p, q exist on the tree.


  • 3
    F

    the better one :

    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if (root == null || p == null || q == null) return null;
        if(root.val<Math.min(p.val,q.val)) return lowestCommonAncestor(root.right,p,q);
        if(root.val>Math.max(p.val,q.val)) return lowestCommonAncestor(root.left,p,q);
        return root;
    }

  • 1

    @sean23 @FrankBian I think u guys can improve without recursion

        public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
            while (true) {
                if (root == null || root == p || root == q) {return root;}
                if (root.val < Math.min(p.val,q.val)) {root = root.right;}
                else if (root.val > Math.max(p.val,q.val)) {root = root.left;}
                else {return root;}
            }
        }
    

Log in to reply
 

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