打印二叉树结构c语言代码
时间: 2023-07-29 12:07:13 浏览: 76
以下是一个简单的打印二叉树结构的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\n", 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->right = (TreeNode*)malloc(sizeof(TreeNode));
root->left->val = 2;
root->right->val = 3;
root->left->left = (TreeNode*)malloc(sizeof(TreeNode));
root->left->right = (TreeNode*)malloc(sizeof(TreeNode));
root->left->left->val = 4;
root->left->right->val = 5;
root->left->left->left = NULL;
root->left->left->right = NULL;
root->left->right->left = NULL;
root->left->right->right = NULL;
root->right->left = NULL;
root->right->right = NULL;
// 打印二叉树
printTree(root, 0);
// 释放内存
free(root->left->left);
free(root->left->right);
free(root->right);
free(root->left);
free(root);
return 0;
}
```
上述代码中,我们定义了一个 `TreeNode` 结构体表示二叉树节点,其中包含了节点值、左右子树指针。`printTree` 函数用于递归打印二叉树,其中需要传入当前节点和当前节点所在的深度。在递归过程中,我们先递归打印右子树,再打印当前节点,最后递归打印左子树。打印当前节点时,我们需要根据节点深度打印一定数量的空格,以便呈现树形结构。最后,我们在 `main` 函数中构造了一个简单的二叉树,并调用 `printTree` 函数将其打印出来。