请您使用C语言来帮我实现这样的操作:输入字符序列,建立二叉树;按先序、中序、后序遍历二叉树(三种递归算法和中序遍历的非递归算法),通过这些步骤来求出二叉树的高度和结点的个数
时间: 2024-05-08 18:19:45 浏览: 102
C语言实现二叉树的前序、中序、后续遍历(递归法)
好的,我知道了。以下是代码实现:
```c
#include <stdio.h>
#include <stdlib.h>
//定义二叉树结构体
typedef struct TreeNode {
char val;
struct TreeNode* left;
struct TreeNode* right;
} TreeNode;
//建立二叉树
TreeNode* buildTree() {
char c = getchar();
if (c == '#') {
return NULL;
}
TreeNode* root = (TreeNode*)malloc(sizeof(TreeNode));
root->val = c;
root->left = buildTree();
root->right = buildTree();
return root;
}
//先序遍历二叉树
void preorderTraversal(TreeNode* root) {
if (root == NULL) {
return;
}
printf("%c ", root->val);
preorderTraversal(root->left);
preorderTraversal(root->right);
}
//中序遍历二叉树
void inorderTraversal(TreeNode* root) {
if (root == NULL) {
return;
}
inorderTraversal(root->left);
printf("%c ", root->val);
inorderTraversal(root->right);
}
//后序遍历二叉树
void postorderTraversal(TreeNode* root) {
if (root == NULL) {
return;
}
postorderTraversal(root->left);
postorderTraversal(root->right);
printf("%c ", root->val);
}
//中序遍历二叉树的非递归算法
void inorderTraversal2(TreeNode* root) {
TreeNode* stack[100];
int top = -1;
TreeNode* p = root;
while (p || top != -1) {
while (p) {
stack[++top] = p;
p = p->left;
}
p = stack[top--];
printf("%c ", p->val);
p = p->right;
}
}
//计算二叉树的高度
int getHeight(TreeNode* root) {
if (root == NULL) {
return 0;
}
int leftHeight = getHeight(root->left);
int rightHeight = getHeight(root->right);
return (leftHeight > rightHeight ? leftHeight : rightHeight) + 1;
}
//计算二叉树的节点个数
int getNodeCount(TreeNode* root) {
if (root == NULL) {
return 0;
}
return getNodeCount(root->left) + getNodeCount(root->right) + 1;
}
int main() {
TreeNode* root = buildTree();
printf("先序遍历结果:");
preorderTraversal(root);
printf("\n中序遍历结果:");
inorderTraversal(root);
printf("\n后序遍历结果:");
postorderTraversal(root);
printf("\n中序遍历(非递归)结果:");
inorderTraversal2(root);
printf("\n二叉树的高度为:%d\n", getHeight(root));
printf("二叉树的节点个数为:%d\n", getNodeCount(root));
return 0;
}
```
阅读全文