日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

数据结构实验之二叉树三:统计叶子数

發布時間:2025/3/21 29 豆豆
生活随笔 收集整理的這篇文章主要介紹了 数据结构实验之二叉树三:统计叶子数 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

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; }

總結

以上是生活随笔為你收集整理的数据结构实验之二叉树三:统计叶子数的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。