Binary Search Tree Iterator II
给一个BST做遍历器.
这题吧, 我答案又不用额外数组的…我做了做实在难…
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class BSTIterator {
List<Integer> l;
int index = -1;
public BSTIterator(TreeNode root) {
l = convert(root);
}
private List<Integer> convert(TreeNode root){
List<Integer> list = new ArrayList<Integer>();
if(root == null)
return list;
list.addAll(convert(root.left));
list.add(root.val);
list.addAll(convert(root.right));
return list;
}
public boolean hasNext() {
return index < l.size() - 1;
}
public int next() {
return l.get(++index);
}
public boolean hasPrev() {
System.out.println(index);
return 0 < index;
}
public int prev() {
return l.get(--index);
}
}
/**
* Your BSTIterator object will be instantiated and called as such:
* BSTIterator obj = new BSTIterator(root);
* boolean param_1 = obj.hasNext();
* int param_2 = obj.next();
* boolean param_3 = obj.hasPrev();
* int param_4 = obj.prev();
*/