Java Inorder Traversal Solution


  • 0
    D

    Just a small variant of ordinary inorder-traversal. Same logic & easy to understand.

    class Solution {
        boolean found = false;
        public TreeNode inorderSuccessor(TreeNode root, TreeNode p) {
            // base case
            if (root == null) return null;
            
            TreeNode left = inorderSuccessor(root.left, p);
            if (left != null) return left; 
            
            if (found == true) return root;
            if (root == p) {
                found = true;
            }
            
            TreeNode right = inorderSuccessor(root.right, p);
            if (right != null) return right;
            return null;
        }  
    }
    

Log in to reply
 

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