diff --git a/leetcode/README.md b/leetcode/README.md index 1e4d0aa1..6388c697 100644 --- a/leetcode/README.md +++ b/leetcode/README.md @@ -30,6 +30,7 @@ LeetCode |153|[Find Minimum in Rotated Sorted Array](https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/) | [C](./src/153.c)|Medium| |160|[Intersection of Two Linked Lists](https://leetcode.com/problems/intersection-of-two-linked-lists/) | [C](./src/160.c)|Easy| |169|[Majority Element](https://leetcode.com/problems/majority-element/) | [C](./src/169.c)|Easy| +|173|[Binary Search Tree Iterator](https://leetcode.com/problems/binary-search-tree-iterator/) | [C](./src/173.c)|Medium| |203|[Remove Linked List Elements](https://leetcode.com/problems/remove-linked-list-elements/) | [C](./src/203.c)|Easy| |206|[Reverse Linked List](https://leetcode.com/problems/reverse-linked-list/) | [C](./src/206.c)|Easy| |215|[Kth Largest Element in an Array](https://leetcode.com/problems/kth-largest-element-in-an-array/) | [C](./src/215.c)|Medium| diff --git a/leetcode/src/173.c b/leetcode/src/173.c new file mode 100644 index 00000000..018ea3eb --- /dev/null +++ b/leetcode/src/173.c @@ -0,0 +1,70 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * struct TreeNode *left; + * struct TreeNode *right; + * }; + */ + +#include + +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); +}