按凹入表形式横向打印二叉树结构c语言代码,用初学者的方法,同时各函数功能相互独立
时间: 2023-12-10 12:41:17 浏览: 35
以下是一个简单的横向打印二叉树结构的C语言代码,各函数功能相互独立。
```c
#include <stdio.h>
#include <stdlib.h>
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
};
// 获取二叉树的高度
int getHeight(struct TreeNode* root) {
if (root == NULL) {
return 0;
}
int leftHeight = getHeight(root->left);
int rightHeight = getHeight(root->right);
return leftHeight > rightHeight ? leftHeight + 1 : rightHeight + 1;
}
// 打印空格
void printSpace(int num) {
for (int i = 0; i < num; i++) {
printf(" ");
}
}
// 打印节点值
void printVal(int val) {
printf("%d", val);
}
// 横向打印二叉树
void printTree(struct TreeNode* root, int level) {
if (root == NULL) {
return;
}
int height = getHeight(root);
int spaceNum = 4 * (1 << (height - level - 1)) - 3;
printTree(root->right, level + 1);
printSpace(spaceNum / 2);
printVal(root->val);
printSpace(spaceNum / 2);
printTree(root->left, level + 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 = (struct TreeNode*)malloc(sizeof(struct TreeNode));
root->left->left->val = 4;
root->left->right = (struct TreeNode*)malloc(sizeof(struct TreeNode));
root->left->right->val = 5;
root->right->left = (struct TreeNode*)malloc(sizeof(struct TreeNode));
root->right->left->val = 6;
root->right->right = (struct TreeNode*)malloc(sizeof(struct TreeNode));
root->right->right->val = 7;
// 横向打印二叉树
printTree(root, 0);
// 释放二叉树内存
free(root->left->left);
free(root->left->right);
free(root->right->left);
free(root->right->right);
free(root->left);
free(root->right);
free(root);
return 0;
}
```
上述代码中,getHeight函数用来获取二叉树的高度;printSpace函数用来打印空格;printVal函数用来打印节点值;printTree函数用来横向打印二叉树;main函数则是构建一个二叉树并打印。各函数功能相互独立,可以单独使用。