Skip to content

Commit ceb1a7e

Browse files
committed
Add Binary Search Tree Iterator
1 parent 3af4f45 commit ceb1a7e

File tree

3 files changed

+73
-0
lines changed

3 files changed

+73
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@ collect some good articles about data structure and algorithm.
3131
10. [排序算法大全](https://zh.wikipedia.org/wiki/Category:排序算法)
3232

3333
## 常用数据结构(Basic Data Structure)
34+
3435
1. [链表(Linked List)](https://zh.wikipedia.org/wiki/链表)
3536
2. [二叉树(Binary Tree)](https://zh.wikipedia.org/wiki/二叉树)
3637
3. [霍夫曼编码(Huffman Coding)](https://zh.wikipedia.org/wiki/霍夫曼编码)
Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
/**
2+
* @Author: Chacha
3+
* @Date: 2018-12-16 21:53:13
4+
* @Last Modified by: Chacha
5+
* @Last Modified time: 2018-12-16 23:03:38
6+
*/
7+
8+
/***********************************************************************************
9+
* Binary Search Tree Iterator
10+
* Implement an iterator over a binary search tree (BST).
11+
* Your iterator will be initialized with the root node of a BST.
12+
* Calling next() will return the next smallest number in the BST.
13+
*
14+
* Example
15+
* For the following binary search tree, in-order traversal by using iterator is [1, 6, 10, 11, 12]
16+
*
17+
* 10
18+
* / \
19+
* 1 11
20+
* \ \
21+
* 6 12
22+
*
23+
* Note: next() and hasNext() should run in average O(1) time and
24+
* uses O(h) memory, where h is the height of the tree.
25+
*
26+
* Source: https://leetcode.com/explore/learn/card/introduction-to-data-structure-binary-search-tree/140
27+
************************************************************************************/
28+
29+
#include <iostream>
30+
#include <vector>
31+
#include <stack>
32+
using namespace std;
33+
34+
/**
35+
* Definition for a binary tree node.
36+
*/
37+
struct TreeNode {
38+
int val;
39+
TreeNode *left;
40+
TreeNode *right;
41+
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
42+
};
43+
44+
45+
class BSTIterator {
46+
private:
47+
stack<TreeNode*> nStack;
48+
TreeNode* curt;
49+
public:
50+
BSTIterator(TreeNode *root) {
51+
curt = root;
52+
}
53+
54+
/** @return whether we have a next smallest number */
55+
bool hasNext() {
56+
return (curt != NULL || !nStack.empty());
57+
}
58+
59+
/** @return the next smallest number */
60+
int next() {
61+
while (curt != NULL) {
62+
nStack.push(curt);
63+
curt = curt->left;
64+
}
65+
66+
if (!nStack.empty()) {
67+
TreeNode* node = nStack.top();
68+
nStack.pop();
69+
curt = curt->right;
70+
}
71+
}
72+
}

0 commit comments

Comments
 (0)