Leetcode: Binary Search Tree Iterator, leetcodeiterator
Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the root node of a BST.Calling next() will return the next smallest number in the BST.Note: next() and hasNext() should run in average O(1) time and uses O(h) memory, where h is the height of the tree.
In fact, the method of this question is to use iterations to traverse BST in a forward order and simulate it with a stack. The reason for iteration is that iteration can output the next element step by step. recursion is done in one breath.
Stack is used for iteration. The maximum stack height is the tree height.
The only question I have about this question is that the average time complexity of next () is O (1). Here average is worth pondering, because it is not every time next () the time complexity is O (1.
Because after a node pop (), the right subtree node needs to be pushed along the left subtree of the right subtree node, until all these steps are pushed to the stack. In this case, I am not sure that the time complexity is O (1), because the time complexity of worst case can reach O (N). For example:
1
\
2
/
3
/
4
After 1-node pop (), 2, 3, and 4 nodes need to be added to the stack in sequence. The complexity of this operation reaches O (N ). But think about it. The time complexity of 4, 3, and 2 is O (1), so the average is O (1. Generally, this is not an extreme example. The left node of Node 2 on the right subtree of Node 1 should be a constant node, so the average inbound stack time should be O (1)
1 /** 2 * Definition for binary tree 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode(int x) { val = x; } 8 * } 9 */10 11 public class BSTIterator {12 Stack<TreeNode> st;13 14 public BSTIterator(TreeNode root) {15 st = new Stack<TreeNode>();16 pushLeft(root);17 }18 19 public void pushLeft(TreeNode root) {20 while (root != null) {21 st.push(root);22 root = root.left;23 }24 }25 26 /** @return whether we have a next smallest number */27 public boolean hasNext() {28 return !st.isEmpty();29 }30 31 /** @return the next smallest number */32 public int next() {33 TreeNode current = st.pop();34 pushLeft(current.right);35 return current.val;36 }37 }38 39 /**40 * Your BSTIterator will be called like this:41 * BSTIterator i = new BSTIterator(root);42 * while (i.hasNext()) v[f()] = i.next();43 */