8ms & 5Line Java code Non-recursive 100%


  • 1
    P

    Based on the fact that BST is ordered. and I simple use the fact of products with the root.

    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
            for(; ;) {
    	        if((p.val - root.val) * (q.val - root.val) <= 0)	return root;
    	        if(p.val < root.val)    root = root.left;
    	        else root = root.right;
            }
        }
    

  • 0
    S

    Excellent! So clever solution. I'll copy it as one of my submission to this question!


  • 0
    D

    This is good
    (p.val - root.val) * (q.val - root.val) <= 0
    Why i didn't think of that, I made so many if there


  • 0
    Z

    This will overflow, when p.val = Integer.MIN_VALUE, q.val = 11, root.val = 10.


Log in to reply
 

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