按先序次序建立一棵二叉树,输入时,以井号表示空指针。对其进行后序遍历,并统计叶子结点的个数。C语言实现
时间: 2024-05-04 15:16:50 浏览: 77
以下是基于递归实现的C代码:
```c
#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 100
typedef struct Node {
char data;
struct Node* left;
struct Node* right;
} Node;
Node* createTree() {
char ch;
Node* root;
scanf("%c", &ch);
if (ch == '#') {
root = NULL;
} else {
root = (Node*)malloc(sizeof(Node));
root->data = ch;
root->left = createTree();
root->right = createTree();
}
return root;
}
int postOrder(Node* root) {
if (root == NULL) {
return 0;
}
int left = postOrder(root->left);
int right = postOrder(root->right);
if (root->left == NULL && root->right == NULL) {
return left + right + 1;
} else {
return left + right;
}
}
int main() {
Node* root = createTree();
int leafNum = postOrder(root);
printf("叶子节点个数为:%d\n", leafNum);
return 0;
}
```
输入示例:`AB#C##DE#F##G###`
输出示例:`叶子节点个数为:4`
阅读全文