按先序次序建立一棵二叉树,输入时,以井号表示空指针。对其进行后序遍历,并统计叶子结点的个数。 c语言代码
时间: 2024-05-02 18:23:28 浏览: 85
以下是按先序次序建立一棵二叉树,后序遍历并统计叶子节点个数的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 *node = (TreeNode*)malloc(sizeof(TreeNode));
node->val = ch;
node->left = createTree();
node->right = createTree();
return node;
}
// 后序遍历并统计叶子节点个数
int postOrder(TreeNode *root, int *count) {
if (!root) {
return 0;
}
int left = postOrder(root->left, count);
int right = postOrder(root->right, count);
if (!root->left && !root->right) {
(*count)++;
}
printf("%c ", root->val);
return left + right + 1;
}
int main() {
TreeNode *root = createTree();
int count = 0;
printf("后序遍历:");
postOrder(root, &count);
printf("\n叶子节点个数:%d\n", count);
return 0;
}
```
输入样例:
```
AB##C##D##
```
输出样例:
```
后序遍历:BCDA
叶子节点个数:2
```
阅读全文