C# Iterative, object equals not value equals.


  • 0
    public TreeNode InorderSuccessor(TreeNode root, TreeNode p) {
        TreeNode lastLeft = null;
        TreeNode node = root;
        while (node != null)
        {
            if (node == p) break;
            else if (p.val <= node.val)
            {
                lastLeft = node;
                node = node.left;
            }
            else
            {
                node = node.right;
            }
        }
        
        if (node == null) return null;
        if (node.right == null) return lastLeft;
        
        node = node.right;
        while (node.left != null)
        {
            node = node.left;
        }
        return node;
    }

Log in to reply
 

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