您的位置:首页 > 其它

LeetCode(173) Binary Search Tree Iterator解题报告

2015-12-15 22:43 316 查看
Implement 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.

解题思路:

下面有两种解法,都可以ac,第一种是直接遍历所有的树节点,然后压入栈中,第二种是不压入所有的树节点,一个出栈,才会将该节点右子树的根节点及往下的所有左子节点压入栈,不需要遍历BST

public class BSTIterator {
Stack<Integer> result;
public BSTIterator(TreeNode root) {
result = deal(root);
}
public Stack<Integer> deal(TreeNode root){
Stack<Integer> res = new Stack<Integer>();
if(root == null)
return res;
res.addAll(deal(root.right));
res.push(root.val);
res.addAll(deal(root.left));
return res;
}

/** @return whether we have a next smallest number */
public boolean hasNext() {
return result.size() != 0 ? true : false;
}

/** @return the next smallest number */
public int next() {
return result.pop();
}
}


public class BSTIterator {
Stack<TreeNode> result;
public BSTIterator(TreeNode root) {
result = new Stack<TreeNode>();
TreeNode temp = root;
while(temp != null){
result.push(temp);
temp = temp.left;
}
}
/** @return whether we have a next smallest number */
public boolean hasNext() {
return result.size() != 0 ? true : false;
}

/** @return the next smallest number */
public int next() {
TreeNode t = result.pop();
TreeNode temp;
if(t.right != null){
result.push(t.right);
temp = result.peek();
while(temp.left != null){
result.push(temp.left);
temp = temp.left;
}
}
return t.val;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: