文章目录
  1. 1. Binary Search Tree Iterator
    1. 1.1. 题目
    2. 1.2. 思路
    3. 1.3. 解题

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.

思路

栈 中序遍历

解题

c++版

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/

class BSTIterator {
public:
stack<TreeNode*> stk;
int nextmin;
BSTIterator(TreeNode *root) {
while(root){
stk.push(root);
root = root->left;
}
}

/** @return whether we have a next smallest number */
bool hasNext() {
if(!stk.empty()){
TreeNode* top = stk.top();
stk.pop();
nextmin = top->val;
TreeNode* cur = top->right;
if(cur){
stk.push(cur);
cur = cur->left;
while(cur){
stk.push(cur);
cur = cur->left;
}
}
return true;
}
else
return false;
}

/** @return the next smallest number */
int next() {
return nextmin;
}
};

/**
* Your BSTIterator will be called like this:
* BSTIterator i = BSTIterator(root);
* while (i.hasNext()) cout << i.next();
*/

Python版

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# Definition for a  binary tree node
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None

class BSTIterator:
# @param root, a binary search tree's root node
def __init__(self, root):
self.nextMin=0
self.stack=[]
while root:
self.stack.append(root)
root=root.left

# @return a boolean, whether we have a next smallest number
def hasNext(self):
if(len(self.stack)!=0):
tmp=self.stack.pop()
self.nextMin=tmp.val
cur=tmp.right
while(cur):
self.stack.append(cur)
cur=cur.left
return True
else:
return False


# @return an integer, the next smallest number
def next(self):
return self.nextMin

# Your BSTIterator will be called like this:
# i, v = BSTIterator(root), []
# while i.hasNext(): v.append(i.next())

文章目录
  1. 1. Binary Search Tree Iterator
    1. 1.1. 题目
    2. 1.2. 思路
    3. 1.3. 解题