Skip to content
This repository was archived by the owner on Sep 20, 2023. It is now read-only.

Commit f1a0db8

Browse files
committed
173 added
1 parent ee16d5f commit f1a0db8

File tree

5 files changed

+145
-56
lines changed

5 files changed

+145
-56
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
# [173. Binary Search Tree Iterator](https://leetcode.com/problems/binary-search-tree-iterator/)
2+
3+
Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the root node of a BST.
4+
5+
Calling next() will return the next smallest number in the BST.
6+
7+
![bst](bst.png)
8+
9+
Example:
10+
11+
```text
12+
BSTIterator iterator = new BSTIterator(root);
13+
iterator.next(); // return 3
14+
iterator.next(); // return 7
15+
iterator.hasNext(); // return true
16+
iterator.next(); // return 9
17+
iterator.hasNext(); // return true
18+
iterator.next(); // return 15
19+
iterator.hasNext(); // return true
20+
iterator.next(); // return 20
21+
iterator.hasNext(); // return false
22+
```
23+
24+
Note:
25+
26+
- next() and hasNext() should run in average O(1) time and uses O(h) memory, where h is the height of the tree.
27+
- You may assume that next() call will always be valid, that is, there will be at least a next smallest number in the BST when next() is called.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
package problem0173
2+
3+
import "github.com/aQuaYi/LeetCode-in-Go/kit"
4+
5+
// TreeNode is pre-defined...
6+
/* Definition for a binary tree node.
7+
* type TreeNode struct {
8+
* Val int
9+
* Left *TreeNode
10+
* Right *TreeNode
11+
* }
12+
*/
13+
type TreeNode = kit.TreeNode
14+
15+
// BSTIterator is the iterator of BST
16+
type BSTIterator struct {
17+
}
18+
19+
// Constructor returns a BST iterator
20+
func Constructor(root *TreeNode) BSTIterator {
21+
22+
return BSTIterator{}
23+
}
24+
25+
// Next returns the next smallest number */
26+
func (it *BSTIterator) Next() int {
27+
28+
return 0
29+
}
30+
31+
// HasNext returns whether we have a next smallest number */
32+
func (it *BSTIterator) HasNext() bool {
33+
34+
return false
35+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
package problem0173
2+
3+
import (
4+
"testing"
5+
6+
"github.com/aQuaYi/LeetCode-in-Go/kit"
7+
"github.com/stretchr/testify/assert"
8+
)
9+
10+
func Test_BSTIterator(t *testing.T) {
11+
ast := assert.New(t)
12+
13+
ints := []int{7, 3, 15, kit.NULL, kit.NULL, 9, 20}
14+
15+
root := kit.Ints2TreeNode(ints)
16+
17+
it := Constructor(root)
18+
19+
i := 0
20+
21+
for it.HasNext() {
22+
for ints[i] == kit.NULL {
23+
i++
24+
}
25+
ast.Equal(ints[i], it.Next(), "%d", ints[i])
26+
}
27+
}
Loading

0 commit comments

Comments
 (0)