# 20150708 lintcode 总结 Binary Search Tree Iterator

403人阅读 评论(0)

#### Binary Search Tree Iterator

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

Challenge

Extra memory usage O(h), h is the height of the tree.

Super Star: Extra memory usage O(1)

/**
* 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:
* Solution iterator = new Solution(root);
* while (iterator.hasNext()) {
*    TreeNode node = iterator.next();
*    do something for node
* }
*/
public class Solution {
public Stack myStack = new Stack();
public TreeNode current;
//@param root: The root of binary tree.
public Solution(TreeNode root) {
// write your code here
current = root;
return;
}

//@return: True if there has next node, or false
public boolean hasNext() {
// write your code here
return (current!=null || !myStack.isEmpty());
}

//@return: return next node
public TreeNode next() {
// write your code here
while(current!=null){
myStack.push(current);
current = current.left;
}
TreeNode res = (TreeNode) myStack.pop();
current = res.right;
return res;
}
}


1. 如果current != null，一直找left.left.left.....就是所求结果；

2. 如果current == null 并且current是 current.parent的left node时，current.parent 就是所求结果，也就是myStack最上面的node；

3. 如果current == null 并且current是 current.parent的right node时， current.parent已经被pop了，current.parent.parent是所求结果，也是myStack最上面的node。

current 为结果时，再从以 current.right 为 root 的 tree 中找 next()， 所以最后要 current = current.right

0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：4512次
• 积分：169
• 等级：
• 排名：千里之外
• 原创：14篇
• 转载：1篇
• 译文：0篇
• 评论：0条
文章分类