#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
};
typedef struct {
int size;
int index;
int nums[10000];
} BSTIterator;
static void dfs(struct TreeNode* root, BSTIterator *obj)
{
if (root == NULL) {
return;
}
dfs(root->left, obj);
obj->nums[obj->size++] = root->val;
dfs(root->right, obj);
}
static struct BSTIterator *bstIteratorCreate(struct TreeNode *root)
{
struct BSTIterator *obj = malloc(sizeof(*obj));
obj->index = 0;
obj->size = 0;
dfs(root, obj);
return iter;
}
/** @return whether we have a next smallest number */
static bool bstIteratorHasNext(struct BSTIterator *obj)
{
return obj->index < obj->size;
}
/** @return the next smallest number */
static int bstIteratorNext(struct BSTIterator *obj)
{
return obj->nums[obj->index++];
}
/** Deallocates memory iteriously allocated for the iterator */
static void bstIteratorFree(struct BSTIterator *obj)
{
free(obj);
}
int main(void)
{
#if 1
struct TreeNode root;
root.val = 7;
struct TreeNode node1[2];
node1[0].val = 3;
node1[1].val = 15;
struct TreeNode node2[4];
node2[2].val = 9;
node2[3].val = 20;
root.left = &node1[0];
root.right = &node1[1];
node1[0].left = NULL;
node1[0].right = NULL;
node1[1].left = &node2[2];
node1[1].right = &node2[3];
#else
struct TreeNode root;
root.val = 1;
struct TreeNode node1[2];
node1[0].val = 2;
node1[1].val = 3;
struct TreeNode node2[4];
node2[0].val = 4;
node2[3].val = 5;
root.left = &node1[0];
root.right = &node1[1];
node1[0].left = &node2[0];
node1[0].right = NULL;
node1[1].left = NULL;
node1[1].right = &node2[3];
#endif
node2[0].left = NULL;
node2[0].right = NULL;
node2[1].left = NULL;
node2[1].right = NULL;
node2[2].left = NULL;
node2[2].right = NULL;
node2[3].left = NULL;
node2[3].right = NULL;
struct BSTIterator *i = bstIteratorCreate(&root);
while (bstIteratorHasNext(i)) {
printf("%d\n", bstIteratorNext(i));
}
bstIteratorFree(i);
return 0;
}
![avatar](https://profile-avatar.csdnimg.cn/default.jpg!1)
Mopes__
- 粉丝: 2332
- 资源: 612
最新资源
- [2212410010302][卢雪燕]实验报告1.doc
- java源码 仿360buy京东商城源码 京东JavaWeb项目源代码.zip
- 计算机课程设计:构建个人博客平台基础教程.md
- JAVAWEB校园订餐系统项目源码.zip
- javaweb物流配货项目源码.zip
- 用LINGO解决数学问题.pdf
- uni-app小型项目
- 自动追频超声波发生器,方案,资料 半桥数码管显示的方案,可直,留邮箱,此款是AVR单片机,和数码管显示的,
- Java 项目-Javaweb仓库管理系统项目源码.zip
- SDR软件无线电开发板ZYNQ7020+AD9361 FPGA+STM32代码原理图资料 送fpga数字图像处理资料
资源上传下载、课程学习等过程中有任何疑问或建议,欢迎提出宝贵意见哦~我们会及时处理!
点击此处反馈
![feedback](https://img-home.csdnimg.cn/images/20220527035711.png)
![feedback](https://img-home.csdnimg.cn/images/20220527035711.png)
![feedback-tip](https://img-home.csdnimg.cn/images/20220527035111.png)