-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathiterator_of_binary_search_tree.cpp
More file actions
57 lines (53 loc) · 1.25 KB
/
Copy pathiterator_of_binary_search_tree.cpp
File metadata and controls
57 lines (53 loc) · 1.25 KB
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
53
54
55
56
57
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
* Example of iterate a tree:
* Solution iterator = Solution(root);
* while (iterator.hasNext()) {
* TreeNode * node = iterator.next();
* do something for node
*/
class Solution {
public:
//@param root: The root of binary tree.
Solution(TreeNode *root) {
// write your code here
index = 0;
m_array.clear();
dfs(root, m_array);
}
//@return: True if there has next node, or false
bool hasNext() {
// write your code here
if (index < m_array.size()) {
return true;
}
return false;
}
//@return: return next node
TreeNode* next() {
// write your code her
if (hasNext())
return m_array[index++];
return NULL;
}
private:
vector<TreeNode*> m_array;
int index;
void dfs(TreeNode* root, vector<TreeNode*> &result) {
if (root == NULL) {
return;
}
dfs(root->left, result);
result.push_back(root);
dfs(root->right, result);
}
};