Design an iterator over a binary search tree with the following rules:
Elements are visited in ascending order (i.e. an in-order traversal)
next() and hasNext() queries run in O(1) time in average.
Example**For the following binary search tree, in-order traversal by using iterator is [1, 6, 10, 11, 12]
············10
···········/ ···
·········1·····11
···········\······ \
············6 ·····12
題目要求next()返回下一個最小的數,其實不難看出是中序遍歷的順序,二叉樹一個性質就是中序遍歷是從小到大的遞增數列,其實這題就是寫一個中序遍歷的迭代器。
遍歷二叉樹有遞歸和迭代的方法,這題用迭代,當然就要用到stack這種后進先出的數據結構。
代碼初始化BSTIterator()的時候就把root和其最左的那條路徑上的nodes都放進stack。
next()方法中,我們先取出當前的準備返回的node, 然后check他的右子樹是否為空,如果為空當然不用做什么,如果不為空,我們就先把它push到stack里面去,然后遍歷它的左子樹放進stack。
/**
* Definition of TreeNode:
* public class TreeNode {
* public int val;
* public TreeNode left, right;
* public TreeNode(int val) {
* this.val = val;
* this.left = this.right = null;
* }
* }
* Example of iterate a tree:
* BSTIterator iterator = new BSTIterator(root);
* while (iterator.hasNext()) {
* TreeNode node = iterator.next();
* do something for node
* }
*/
public class BSTIterator {
//@param root: The root of binary tree.
Stack<TreeNode> stack = new Stack<>();
public BSTIterator(TreeNode root) {
// write your code here
while(root != null) { //firs push root and all the left most line nodes to stack
stack.push(root);
root = root.left;
}
}
//@return: True if there has next node, or false
public boolean hasNext() {
// write your code here
return !stack.isEmpty();
}
//@return: return next node
public TreeNode next() {
// write your code here
TreeNode node = stack.pop();
if( node.right != null) { //if the poped out node has right subtree, we need push the nodes in stack
TreeNode nextPush = node.right;
stack.push(nextPush); //push the right node
while(nextPush.left != null ) { // push the left most line of nodes of the right node
stack.push(nextPush.left);
nextPush = nextPush.left;
}
}
return node;
}
}