LintCode 86. 二叉查詢樹迭代器
阿新 • • 發佈:2019-02-18
題目: 二叉查詢樹迭代器
要求:
設計實現一個帶有下列屬性的二叉查詢樹的迭代器:
- 元素按照遞增的順序被訪問(比如中序遍歷)
- next()和hasNext()的詢問操作要求均攤時間複雜度是O(1)
樣例:
對於下列二叉查詢樹,使用迭代器進行中序遍歷的結果為 [1, 6, 10, 11, 12]
10
/ \
1 11
\ \
6 12
演算法要求:
額外空間複雜度是O(h),其中h是這棵樹的高度
Super Star:使用O(1)的額外空間複雜度
解題思路:
直接用List來存,接著用List的Iterator
演算法如下:
/**
* 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 {
private LinkedList<TreeNode> list;
Iterator<TreeNode> it;
/*
* @param root: The root of binary tree.
*/
public BSTIterator(TreeNode root) {
// do intialization if necessary
list = new LinkedList<TreeNode>();
Stack<TreeNode> stack = new Stack();
TreeNode temp = root;
while (temp != null || !stack.empty()) {
while (temp != null) {
stack.add(temp);
temp = temp.left;
}
temp = stack.pop();
list.add(temp);
temp = temp.right;
}
it = list.iterator();
}
/*
* @return: True if there has next node, or false
*/
public boolean hasNext() {
// write your code here
return it.hasNext();
}
/*
* @return: return next node
*/
public TreeNode next() {
// write your code here
return it.next();
}
}