c语言先序遍历可视化用easyX
时间: 2023-06-20 11:06:45 浏览: 54
好的,下面是使用 easyX 实现 c 语言二叉树先序遍历可视化的代码。首先,需要安装 easyX 并配置好环境,然后创建一个空白项目,将以下代码复制到 main.cpp 中并运行即可。
```c++
#include <graphics.h>
#include <iostream>
using namespace std;
const int MAXN = 10005;
int biTree[MAXN];
int curIndex = 0;
void createBiTree(int biTree[], int &curIndex)
{
int value;
cin >> value;
if (value != -1)
{
biTree[curIndex++] = value;
createBiTree(biTree, curIndex);
createBiTree(biTree, curIndex);
}
else
{
biTree[curIndex++] = -1;
}
}
void drawBiTree(int biTree[], int index, int x, int y, int depth)
{
if (biTree[index] == -1)
{
return;
}
char buf[10];
settextcolor(WHITE);
setbkcolor(BLACK);
settextstyle(20, 0, "Arial");
sprintf_s(buf, "%d", biTree[index]);
outtextxy(x, y, buf);
int step = 100 / (depth + 1);
if (biTree[index * 2 + 1] != -1)
{
line(x, y + 20, x - step, y + 50);
drawBiTree(biTree, index * 2 + 1, x - step, y + 50, depth + 1);
}
if (biTree[index * 2 + 2] != -1)
{
line(x, y + 20, x + step, y + 50);
drawBiTree(biTree, index * 2 + 2, x + step, y + 50, depth + 1);
}
}
int main()
{
initgraph(800, 600);
setbkcolor(BLACK);
cleardevice();
createBiTree(biTree, curIndex);
drawBiTree(biTree, 0, 400, 50, 1);
system("pause");
closegraph();
return 0;
}
```
在运行时,需要按照先序遍历的顺序输入二叉树的节点值,-1 表示空节点。例如,输入 1 2 -1 -1 3 4 -1 -1 5 -1 -1 后,程序会根据这些值构建出如下的二叉树:
```
1
/ \
2 3
/ \
4 5
```
然后,程序会将这棵二叉树绘制在窗口中,如下图所示:
![c语言先序遍历可视化](https://img-blog.csdnimg.cn/20211008103250515.png)