用C语言创造一个二叉树,用#代表空结点,并求二叉树的高度
时间: 2024-03-01 11:25:31 浏览: 74
以下是用C语言实现的二叉树,其中使用了递归方法求二叉树的高度:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct TreeNode {
char val;
struct TreeNode *left;
struct TreeNode *right;
} TreeNode;
// 创建二叉树
TreeNode* createTree() {
char ch;
scanf("%c", &ch);
if (ch == '#') {
return NULL;
}
TreeNode* root = (TreeNode*)malloc(sizeof(TreeNode));
root->val = ch;
root->left = createTree();
root->right = createTree();
return root;
}
// 求二叉树高度
int getHeight(TreeNode* root) {
if (root == NULL) {
return 0;
}
int leftHeight = getHeight(root->left);
int rightHeight = getHeight(root->right);
return 1 + (leftHeight > rightHeight ? leftHeight : rightHeight);
}
int main() {
printf("请输入二叉树(用#代表空结点):\n");
TreeNode* root = createTree();
printf("二叉树的高度为:%d\n", getHeight(root));
return 0;
}
```
示例输入:`AB#D##C##`,表示以下二叉树:
```
A
/ \
B C
\
D
```
输出:`二叉树的高度为:3`
阅读全文