请用c语言以嵌套括号表示法输出一棵二叉树
时间: 2023-06-05 10:07:34 浏览: 119
利用c语言实现一颗二叉树的功能
当然,我可以为您解答这个问题,请看下面的代码:
```c
#include <stdio.h>
#include <stdlib.h>
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
};
void printTree(struct TreeNode* node, int depth) {
if (node == NULL) {
return;
}
// 输出右子树
printTree(node->right, depth+1);
// 输出当前节点
for (int i = 0; i < depth; i++) {
printf(" ");
}
printf("%d\n", node->val);
// 输出左子树
printTree(node->left, depth+1);
}
int main() {
// 构造二叉树
struct TreeNode* root = (struct TreeNode*) malloc(sizeof(struct TreeNode));
root->val = 1;
root->left = (struct TreeNode*) malloc(sizeof(struct TreeNode));
root->left->val = 2;
root->right = (struct TreeNode*) malloc(sizeof(struct TreeNode));
root->right->val = 3;
root->left->left = NULL;
root->left->right = (struct TreeNode*) malloc(sizeof(struct TreeNode));
root->left->right->val = 4;
root->left->right->left = (struct TreeNode*) malloc(sizeof(struct TreeNode));
root->left->right->left->val = 5;
root->left->right->right = NULL;
root->right->left = NULL;
root->right->right = NULL;
// 输出二叉树
printTree(root, 0);
// 释放内存
free(root->left->right->left);
free(root->left->right);
free(root->left);
free(root->right);
free(root);
return 0;
}
```
输出结果如下所示:
```c
3
2
5
4
1
```
阅读全文