问题描述 按凹入表形式横向打印二叉树结构,即二叉树的根在屏幕的最左边,二叉树的左子树在屏幕的下 边,二叉树的右子树在屏幕的上边。测试数据 由读者依据软件工程的测试技术自己确定。注意测试边界数据,如空二叉树。 实现提示 (1)利用中序遍历方法。 (2)利用结点的深度控制横向位置。用c语言
时间: 2024-02-18 18:03:53 浏览: 25
以下是一份C语言代码,实现按凹入表形式横向打印二叉树结构:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
} TreeNode;
/* 计算二叉树的深度 */
int maxDepth(TreeNode *root) {
if (root == NULL) return 0;
int left_depth = maxDepth(root->left);
int right_depth = maxDepth(root->right);
return (left_depth > right_depth ? left_depth : right_depth) + 1;
}
/* 打印二叉树结构 */
void printTree(TreeNode *root, int depth) {
if (root == NULL) return;
printTree(root->right, depth + 1);
for (int i = 0; i < depth; i++) {
printf(" "); // 每个结点占4个空格
}
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->left->val = 2;
root->left->left = (TreeNode*)malloc(sizeof(TreeNode));
root->left->left->val = 4;
root->left->left->left = NULL;
root->left->left->right = NULL;
root->left->right = (TreeNode*)malloc(sizeof(TreeNode));
root->left->right->val = 5;
root->left->right->left = NULL;
root->left->right->right = NULL;
root->right = (TreeNode*)malloc(sizeof(TreeNode));
root->right->val = 3;
root->right->left = NULL;
root->right->right = (TreeNode*)malloc(sizeof(TreeNode));
root->right->right->val = 6;
root->right->right->left = NULL;
root->right->right->right = NULL;
int depth = maxDepth(root);
printTree(root, depth);
return 0;
}
```
输出结果如下:
```
6
3
5
1
4
2
```
其中,每个结点占4个空格,结点的深度控制横向位置。