LeetCode Binary Search Tree Iterator

时间:2023-03-08 18:18:17

原题链接在这里:https://leetcode.com/problems/binary-search-tree-iterator/

题目:

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.

题解:

用一个stack把所有最左边的node压进 stack中。

判断hasNext()时就是看stack 是否为空.

next()返回stack顶部top元素,若是top有右子树,就把右子树的所有最左node压入stack中.

constructor time complexity: O(h).

hashNext time complexity: O(1).

next time complexity: O(h).

Space: O(h), stack 最大为树的高度。

AC Java:

 /**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/ public class BSTIterator {
Stack<TreeNode> stk; public BSTIterator(TreeNode root) {
stk = new Stack<TreeNode>();
while(root != null){
stk.push(root);
root = root.left;
}
} /** @return whether we have a next smallest number */
public boolean hasNext() {
return !stk.isEmpty();
} /** @return the next smallest number */
public int next() {
TreeNode top = stk.pop();
TreeNode rightLeft = top.right;
while(rightLeft != null){
stk.push(rightLeft);
rightLeft = rightLeft.left;
} return top.val;
}
} /**
* Your BSTIterator will be called like this:
* BSTIterator i = new BSTIterator(root);
* while (i.hasNext()) v[f()] = i.next();
*/

类似Binary Tree Inorder TraversalInorder Successor in BST.