[LeetCode] Binary Search Tree Iterator
來(lái)源:程序員人生 發(fā)布時(shí)間:2015-01-16 08:52:29 閱讀次數(shù):2674次
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.
這是1道很經(jīng)典的題目,考的非遞歸的中序遍歷。其實(shí)這道題等價(jià)于寫(xiě)1個(gè)2叉樹(shù)中序遍歷的迭代器。需要內(nèi)置1個(gè)棧,1開(kāi)始先存儲(chǔ)到最左葉子節(jié)點(diǎn)的路徑。在遍歷的進(jìn)程中,只要當(dāng)前節(jié)點(diǎn)存在右孩子,則進(jìn)入右孩子,存除從此處開(kāi)始到當(dāng)前子樹(shù)里最左葉子節(jié)點(diǎn)的路徑。
public class BSTIterator {
Stack<TreeNode> stack;
public BSTIterator(TreeNode root) {
stack = new Stack<TreeNode>();
while (root != null) {
stack.push(root);
root = root.left;
}
}
/** @return whether we have a next smallest number */
public boolean hasNext() {
return !stack.isEmpty();
}
/** @return the next smallest number */
public int next() {
TreeNode node = stack.pop();
int ret = node.val;
if (node.right != null) {
node = node.right;
while (node != null) {
stack.push(node);
node = node.left;
}
}
return ret;
}
}
生活不易,碼農(nóng)辛苦
如果您覺(jué)得本網(wǎng)站對(duì)您的學(xué)習(xí)有所幫助,可以手機(jī)掃描二維碼進(jìn)行捐贈(zèng)