3 lines non-recursive solution in Java


  • 8
    I
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        while(true){
          if((root.val-p.val)*(root.val-q.val) <= 0) return root;
          root = p.val < root.val ? root.left : root.right;
        }
    }

Log in to reply
 

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