Java Iterative Solution, concise and easy to understand


  • 8
    S
    public TreeNode inorderSuccessor(TreeNode root, TreeNode p) {
             TreeNode ret = null;
            while (root != null) {
                if (root.val <= p.val) {
                    root = root.right;
                } else {
                    ret = root;
                    root = root.left;
                }
            }
            return ret;
    }
    

  • 6
    Y

    Concise and efficient. Love this answer. Let me add comments

    	public TreeNode inorderSuccessor(TreeNode root, TreeNode p) {
    		
    		TreeNode ret = null;
    		while (root != null) {
    			// 1. current root is smaller or equal, definitely not in this branch
    			if (root.val <= p.val) {
    				root = root.right;
    			// 2. current root is bigger, definitely in this branch				
    			} else {
    				// 2.1 root is 1 of the successors, although might not be the one
    				ret = root;
    				// 2.2 maybe we can find a closer successor in the left branch
    				root = root.left;
    			}
    		}
    		return ret;
    	}
    

  • 0
    F

    love the solution; also love the comments


  • 0

    @shen5630 said in Java Iterative Solution, concise and easy to understand:

    public TreeNode inorderSuccessor(TreeNode root, TreeNode p) {
    TreeNode ret = null;
    while (root != null) {
    if (root.val <= p.val) {
    root = root.right;
    } else {
    ret = root;
    root = root.left;
    }
    }
    return ret;
    }

    Wonderfull!


Log in to reply
 

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