forked from TheAlgorithms/C
-
Notifications
You must be signed in to change notification settings - Fork 0
/
173.c
78 lines (70 loc) · 1.68 KB
/
173.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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
#include <limits.h>
typedef struct
{
int *values;
int CurrentIndex;
int NumberOfNodes;
} BSTIterator;
void TraverseAndAssign(struct TreeNode *root, BSTIterator *obj)
{
if (!root)
return;
if (root->left)
TraverseAndAssign(root->left, obj);
obj->values[obj->CurrentIndex] = root->val;
obj->CurrentIndex++;
if (root->right)
TraverseAndAssign(root->right, obj);
}
int TotalNodes(struct TreeNode *root)
{
if (!root)
return 0;
int nodes_left = TotalNodes(root->left);
int nodes_right = TotalNodes(root->right);
return nodes_left + nodes_right + 1;
}
BSTIterator *bSTIteratorCreate(struct TreeNode *root)
{
int n = TotalNodes(root);
int size = n + 1;
printf("%d", size);
BSTIterator *obj = (BSTIterator *)malloc(sizeof(BSTIterator));
obj->values = (int *)calloc(size, sizeof(int));
obj->CurrentIndex = 0;
obj->NumberOfNodes = n;
obj->values[size - 1] = INT_MAX;
TraverseAndAssign(root, obj);
obj->CurrentIndex = 0;
return obj;
}
/** @return the next smallest number */
int bSTIteratorNext(BSTIterator *obj)
{
int NextValue = obj->values[obj->CurrentIndex];
obj->CurrentIndex++;
return NextValue;
}
/** @return whether we have a next smallest number */
bool bSTIteratorHasNext(BSTIterator *obj)
{
if (!obj->NumberOfNodes)
{
return false;
}
printf(" Here ");
return (obj->values[obj->CurrentIndex] == INT_MAX) ? false : true;
}
void bSTIteratorFree(BSTIterator *obj)
{
free(obj->values);
free(obj);
}