Java solution same as iterative in-order traversal


  • 0
    E

    Tree In-order traversal

    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> res = new ArrayList<>();
        Deque<TreeNode> stack = new ArrayDeque<TreeNode>();
        while (root != null || !stack.isEmpty()){
            while (root != null){
                stack.push(root);
                root = root.left;
            }
            root = stack.pop();
            res.add(root.val);
            root = root.right;
        }
        return res;
    }
    

    BST Iterator

    public class BSTIterator {
    
        private Deque<TreeNode> stack;
        private TreeNode cur;
    
        public BSTIterator(TreeNode root) {
            stack = new ArrayDeque<>();
            cur = root;
            while (cur != null){
                stack.push(cur);
                cur = cur.left;
            }
        }
    
        /** @return whether we have a next smallest number */
        public boolean hasNext() {
            return cur != null || !stack.isEmpty();
        }
    
        /** @return the next smallest number */
        public int next() {
            int val = 0;
            while (cur != null){
                stack.push(cur);
                cur = cur.left;
            }
            cur = stack.pop();
            val = cur.val;
            cur = cur.right;        
            return val;
        }
    }
    

Log in to reply
 

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