An easy,concise solution using stack


  • 0
    C
    public class BSTIterator {
        TreeNode node;
        Stack<TreeNode> stack = new Stack<TreeNode>();
        public BSTIterator(TreeNode root) {
            node = root;
        }
    
        public boolean hasNext() {
            return node != null || stack.size() != 0;
        }
    
        public int next() {
            while (node != null) {
                stack.push(node);
                node = node.left;
            }
    
            node = stack.pop();
            int r = node.val;
            node = node.right;
            return r;
        }
    }

Log in to reply
 

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