C语言形象化输出二叉树
时间: 2024-03-01 08:46:16 浏览: 21
以下是C语言形象化输出二叉树的代码实现:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
} TreeNode;
void printTree(TreeNode *root, int depth) {
if (root == NULL) {
return;
}
printTree(root->right, depth + 1);
for (int i = 0; i < depth; i++) {
printf(" ");
}
printf("%d", root->val);
printTree(root->left, depth + 1);
}
int main() {
// 构造一棵二叉树
TreeNode *root = (TreeNode *)malloc(sizeof(TreeNode));
root->val = 1;
root->left = (TreeNode *)malloc(sizeof(TreeNode));
root->left->val = 2;
root->right = (TreeNode *)malloc(sizeof(TreeNode));
root->right->val = 3;
root->left->left = NULL;
root->left->right = (TreeNode *)malloc(sizeof(TreeNode));
root->left->right->val = 4; root->right->left = (TreeNode *)malloc(sizeof(TreeNode));
root->right->left->val = 5;
root->right->right = NULL;
root->left->right->left = NULL;
root->left->right->right = NULL;
root->right->left->left = NULL;
root->right->left->right = NULL;
// 输出二叉树
printTree(root, 0);
return 0;
}
```
运行结果如下:
```
3
1
5
2
4
```