Binary Search Tree Iterator
Problem:
3/16/2018 update:
Remember to check cur != null in hasNext(). Stack might be empty but we still have cur.
--------------------------------------------------------------------------------------------------------------------------
This problem is the breakdown of "binary search tree inorder traversal" iterative version. Let's first see the code of the iterative version:
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:
Analysis:next()
and hasNext()
should run in average O(1) time and uses O(h) memory, where h is the height of the tree.3/16/2018 update:
Remember to check cur != null in hasNext(). Stack might be empty but we still have cur.
public class BSTIterator { Stack<TreeNode> stack; TreeNode cur; public BSTIterator(TreeNode root) { stack = new Stack<>(); cur = root; } /** @return whether we have a next smallest number */ public boolean hasNext() { return !stack.isEmpty() || cur != null; } /** @return the next smallest number */ public int next() { while (cur != null) { stack.push(cur); cur = cur.left; } TreeNode temp = stack.pop(); cur = temp.right; return temp.val; } } /** * Your BSTIterator will be called like this: * BSTIterator i = new BSTIterator(root); * while (i.hasNext()) v[f()] = i.next(); */
--------------------------------------------------------------------------------------------------------------------------
This problem is the breakdown of "binary search tree inorder traversal" iterative version. Let's first see the code of the iterative version:
public class Solution {
public List < Integer > inorderTraversal(TreeNode root) {
List < Integer > res = new ArrayList < > ();
Stack < TreeNode > stack = new Stack < > ();
TreeNode curr = root;
while (curr != null || !stack.isEmpty()) {
while (curr != null) {
stack.push(curr);
curr = curr.left;
}
curr = stack.pop();
res.add(curr.val);
curr = curr.right;
}
return res;
}
}
If we only check the second while loop, we can see that it's the implementation of next() function. And the condition of the first while loop: curr != null || ! stack.isEmpty() is the implementation of hasNext() function.
评论
发表评论