数据结构实验之二叉树三:统计叶子数
生活随笔
收集整理的這篇文章主要介紹了
数据结构实验之二叉树三:统计叶子数
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
Description
已知二叉樹的一個按先序遍歷輸入的字符序列,如abc,de,g,f, (其中,表示空結點)。請建立二叉樹并求二叉樹的葉子結點個數。
Input
連續輸入多組數據,每組數據輸入一個長度小于50個字符的字符串。
Output
輸出二叉樹的葉子結點個數。
Sample
Input
abc,de,g,f,
Output
3
Hint
#include<bits/stdc++.h>using namespace std;typedef struct node {char data;struct node *l, *r; } Tree;char pre[55]; int cnt, leaves; Tree* creat() {Tree* root;if(pre[cnt] == ','){cnt++;root = NULL;}else{root = new Tree;root->data = pre[cnt++];root->l = creat();root->r = creat();}return root; } void count_leaves(Tree *root) {if(root){if(!root->l && !root->r){leaves++;}count_leaves(root->l);count_leaves(root->r);} } int main() {while(~scanf("%s", pre)){cnt = 0;leaves = 0;Tree *root = creat();count_leaves(root);printf("%d\n", leaves);}return 0; }總結
以上是生活随笔為你收集整理的数据结构实验之二叉树三:统计叶子数的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 骄傲的代价_JAVA
- 下一篇: 数据结构实验之二叉树二:遍历二叉树