层序遍历二叉树可视化easyx代码,改变遍历的节点的颜色
时间: 2023-06-25 13:02:51 浏览: 33
以下是基于EasyX图形库的二叉树可视化和层序遍历代码,其中节点颜色的改变使用了随机颜色函数:
```c++
#include <graphics.h>
#include <queue>
#include <ctime>
#define MAXN 1000
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
// 随机颜色函数
COLORREF randomColor() {
return RGB(rand() % 256, rand() % 256, rand() % 256);
}
// 绘制节点
void drawNode(int x, int y, int val, COLORREF color) {
setfillcolor(color);
setlinecolor(RGB(0, 0, 0));
fillellipse(x, y, 15, 15);
settextcolor(RGB(255, 255, 255));
char s[10];
sprintf_s(s, "%d", val);
outtextxy(x - 6, y - 7, s);
}
// 绘制线段
void drawLine(int x1, int y1, int x2, int y2) {
setlinecolor(RGB(0, 0, 0));
line(x1, y1, x2, y2);
}
// 层序遍历并绘制二叉树
void levelOrder(TreeNode* root, int x0, int y0, int h, int w) {
std::queue<TreeNode*> q;
q.push(root);
int cnt = 0, lastNodeIndex = 1, thisNodeIndex = 0;
while (!q.empty()) {
thisNodeIndex = 0;
for (int i = 1; i <= lastNodeIndex; i++) {
TreeNode* t = q.front();
q.pop();
int x = x0 + (i * w) - (w / 2);
int y = y0 + (h * cnt);
drawNode(x, y, t->val, randomColor());
if (t->left) {
q.push(t->left);
thisNodeIndex++;
drawLine(x, y, x0 + (thisNodeIndex * w) - (w / 2), y + h);
}
if (t->right) {
q.push(t->right);
thisNodeIndex++;
drawLine(x, y, x0 + (thisNodeIndex * w) - (w / 2), y + h);
}
}
cnt++;
lastNodeIndex = thisNodeIndex;
}
}
int main() {
initgraph(800, 600);
srand(time(NULL));
TreeNode* root = new TreeNode(1);
root->left = new TreeNode(2);
root->right = new TreeNode(3);
root->left->left = new TreeNode(4);
root->left->right = new TreeNode(5);
root->right->left = new TreeNode(6);
root->right->right = new TreeNode(7);
levelOrder(root, 400, 50, 80, 120);
_getch();
closegraph();
return 0;
}
```
需要注意的是,由于使用了随机颜色函数,每次运行时节点的颜色会有所不同。
相关推荐
![cpp](https://img-home.csdnimg.cn/images/20210720083646.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)