Leetcode[173] Binary Search Tree Iterator
15 Nov 2015###Task1 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. ###Python
# Definition for a binary tree node
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class BSTIterator(object):
def __init__(self, root):
"""
:type root: TreeNode
"""
self.stack = []
self.prev = root
def hasNext(self):
"""
:rtype: bool
"""
return len(self.stack) > 0 or self.prev
def next(self):
"""
:rtype: int
"""
while len(self.stack) > 0 or self.prev:
while self.prev:
self.stack.append(self.prev)
self.prev = self.prev.left
cur = self.stack.pop()
self.prev = cur.right
return cur.val
# Your BSTIterator will be called like this:
# i, v = BSTIterator(root), []
# while i.hasNext(): v.append(i.next())
###Java
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class BSTIterator {
Stack<TreeNode> stack = new Stack<TreeNode>();
TreeNode cur;
public BSTIterator(TreeNode root) {
cur = root;
}
/** @return whether we have a next smallest number */
public boolean hasNext() {
return (cur != null || !stack.isEmpty());
}
/** @return the next smallest number */
public int next() {
while (cur != null) {
stack.push(cur);
cur = cur.left;
}
cur = stack.pop();
TreeNode res = cur;
cur = cur.right;
return res.val;
}
}
/**
* Your BSTIterator will be called like this:
* BSTIterator i = new BSTIterator(root);
* while (i.hasNext()) v[f()] = i.next();
*/
###Points
- O(n)
- Inorder traversal space -> O(n) instead of O(h)