最快方法理解:先序序列为abcd的不同二叉树个数

因为各种不同的4结点二叉树总能对应上先序序列为abcd,因此用卡特兰树求一下树的个数就行

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
下面是用C语言实现先序遍历序列建立二叉树的代码: ```c #include <stdio.h> #include <stdlib.h> // 定义二叉树的结构体 typedef struct TreeNode { char data; // 数据域 struct TreeNode* leftChild; // 左子树指针 struct TreeNode* rightChild; // 右子树指针 } TreeNode; // 先序遍历序列建立二叉树 TreeNode* buildTree() { char c; scanf("%c", &c); if (c == '#') { return NULL; } TreeNode* root = (TreeNode*)malloc(sizeof(TreeNode)); root->data = c; root->leftChild = buildTree(); root->rightChild = buildTree(); return root; } // 统计二叉树中叶子结点个数 int countLeaves(TreeNode* root) { if (root == NULL) { return 0; } if (root->leftChild == NULL && root->rightChild == NULL) { return 1; } return countLeaves(root->leftChild) + countLeaves(root->rightChild); } // 计算二叉树的深度 int calcDepth(TreeNode* root) { if (root == NULL) { return 0; } int leftDepth = calcDepth(root->leftChild); int rightDepth = calcDepth(root->rightChild); return leftDepth > rightDepth ? leftDepth + 1 : rightDepth + 1; } int main() { printf("请输入先序遍历序列:"); TreeNode* root = buildTree(); printf("二叉树叶子结点个数:%d\n", countLeaves(root)); printf("二叉树的深度:%d\n", calcDepth(root)); return 0; } ``` 这里采用了递归的方式实现了先序遍历序列建立二叉树、统计二叉树中叶子结点个数和计算二叉树的深度。其中,函数`countLeaves()`用于统计二叉树中叶子结点个数,函数`calcDepth()`用于计算二叉树的深度。 运行结果如下: ``` 请输入先序遍历序列:AB#D##CE### 二叉树叶子结点个数:3 二叉树的深度:3 ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值