173. Binary Search Tree Iterator
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.
本题目的本质是二叉树的中序遍历
public class BSTIterator {
private Stack<TreeNode> stk;
public BSTIterator(TreeNode root) {
stk = new Stack<>();
// 先找到第一个节点,并把路径入栈
while (root != null) {
stk.push(root);
root = root.left;
}
}
/**
* @return whether we have a next smallest number
*/
public boolean hasNext() {
// 栈为空时不再有下一个
return !stk.isEmpty();
}
/**
* @return the next smallest number
*/
public int next() {
TreeNode curr = stk.pop();
int res = curr.val;
// 如果该元素有右节点,把它的右节点及右节点的所有左边节点都压入栈中
curr = curr.right;
while (curr != null) {
stk.push(curr);
curr = curr.left;
}
return res;
}
}
二叉树的中序遍历非递归
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> list = new ArrayList<>();
if (root == null)
return list;
Stack<TreeNode> stack = new Stack<>();
while (root != null || !stack.isEmpty()) {
if (root != null) {
stack.push(root);
root = root.left;
} else {
root = stack.pop();
list.add(root.val);
root = root.right;
}
}
return list;
}