c语言 定义二叉树的数据,创建一颗二叉树并遍历,计算其高度 完整代码
时间: 2024-01-23 18:02:53 浏览: 71
完整代码如下:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
} TreeNode;
TreeNode* createTree() {
int val;
scanf("%d", &val);
if (val == -1) {
return NULL;
}
TreeNode* root = (TreeNode*)malloc(sizeof(TreeNode));
root->val = val;
root->left = createTree();
root->right = createTree();
return root;
}
void preOrder(TreeNode* root) {
if (!root) {
return;
}
printf("%d ", root->val);
preOrder(root->left);
preOrder(root->right);
}
void inOrder(TreeNode* root) {
if (!root) {
return;
}
inOrder(root->left);
printf("%d ", root->val);
inOrder(root->right);
}
void postOrder(TreeNode* root) {
if (!root) {
return;
}
postOrder(root->left);
postOrder(root->right);
printf("%d ", root->val);
}
int getHeight(TreeNode* root) {
if (!root) {
return 0;
}
int leftHeight = getHeight(root->left);
int rightHeight = getHeight(root->right);
int height = leftHeight > rightHeight ? leftHeight : rightHeight;
return height + 1;
}
int main() {
TreeNode* root = createTree();
printf("PreOrder: ");
preOrder(root);
printf("\n");
printf("InOrder: ");
inOrder(root);
printf("\n");
printf("PostOrder: ");
postOrder(root);
printf("\n");
int height = getHeight(root);
printf("Height: %d\n", height);
return 0;
}
```
这个程序可以通过输入构建一颗二叉树,并且支持前序、中序、后序遍历,同时还可以计算二叉树的高度。
阅读全文