本文共 1129 字,大约阅读时间需要 3 分钟。
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 Stackstack; public BSTIterator(TreeNode root) { stack = new Stack (); TreeNode tempNode = root; if(root!=null) { while(tempNode != null){ stack.push(tempNode); tempNode = tempNode.left; } } } /** @return whether we have a next smallest number */ public boolean hasNext() { return !stack.empty(); } /** @return the next smallest number */ public int next() { TreeNode node = stack.pop(); TreeNode tempNode = node.right; if(tempNode!=null){ while(tempNode!=null){ stack.push(tempNode); tempNode = tempNode.left; } } return node.val; }}
转载地址:http://piuni.baihongyu.com/