标签:
mplement 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. Credits: Special thanks to @ts for adding this problem and creating all test cases.
import java.util.ArrayDeque;
import java.util.Stack;
public class BSTIterator {
private ArrayDeque<TreeNode> mArrayDeque;
public BSTIterator(TreeNode root) {
mArrayDeque = new ArrayDeque<TreeNode>();
bTreeInorderTraverse(root);
}
private void bTreeInorderTraverse(TreeNode root) {
TreeNode p = root;
Stack<TreeNode> tmpStack = new Stack<TreeNode>();
while (p != null || ! tmpStack.empty()) {
if (p != null) {
tmpStack.push(p);
p = p.left;
} else {
p = tmpStack.pop();
mArrayDeque.add(p);
p = p.right;
}
}
}
public boolean hasNext() {
return ! mArrayDeque.isEmpty();
}
public int next() {
if (hasNext()) {
return mArrayDeque.poll().val;
} else {
return -1;
}
}
public static class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
}
import java.util.Stack;
public class BSTIterator {
private Stack<TreeNode> mStack;
public BSTIterator(TreeNode root) {
mStack = new Stack<TreeNode>();
while (root != null) {
mStack.push(root);
root = root.left;
}
}
public boolean hasNext() {
return ! mStack.empty();
}
public int next() {
TreeNode p = mStack.pop();
int res = p.val;
if (p.right != null) {
TreeNode node = p.right;
while (node != null) {
mStack.push(node);
node = node.left;
}
}
return res;
}
public static class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
}[LeetCode]Binary Search Tree Iterator,解题报告
标签:
原文地址:http://blog.csdn.net/wzy_1988/article/details/43675445