Simple iterative Java solution that beats 98%


  • 0
    L

    The idea is to iterate left and right till you find the right node. I noticed that the order of the arguments may be anywhere from lower to higher and vice versa to added additional checks. Here is the code:

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

Log in to reply
 

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