日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

二叉树(前序遍历序列、中序遍历序列、后序遍历序列、层次遍历序列、深度、叶子数)

發(fā)布時間:2025/3/21 编程问答 28 豆豆
生活随笔 收集整理的這篇文章主要介紹了 二叉树(前序遍历序列、中序遍历序列、后序遍历序列、层次遍历序列、深度、叶子数) 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

Description

已知二叉樹的一個按前序遍歷輸入的字符序列,如abc,de,g,f, (其中,表示空結(jié)點)。請建立二叉樹,并輸出建立二叉樹的前序遍歷序列、中序遍歷序列、后序遍歷序列、層次遍歷序列、深度、葉子數(shù)。
Input

多組測試數(shù)據(jù),對于每組測試數(shù)據(jù),輸入一個長度小于50的按前序遍歷輸入的字符序列。
Output

對于每組測試數(shù)據(jù),第1行輸出其前序遍歷序列、第2行輸出其中序遍歷序列、第3行輸出其后序遍歷序列、第4行輸出其層次遍歷序列、第5行輸出其深度、第6行輸出其葉子數(shù)。

Sample

Input
abc,de,g,f,

Output

abcdegf
cbegdfa
cgefdba
abcdefg
5
3

#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 preoreder(Tree *root) {if(root){printf("%c", root->data);preoreder(root->l);preoreder(root->r);} }void midoreder(Tree *root) {if(root){midoreder(root->l);printf("%c", root->data);midoreder(root->r);} }void posoreder(Tree *root) {if(root){posoreder(root->l);posoreder(root->r);printf("%c", root->data);} }void cengxu(Tree *root)//模擬隊列 {Tree * que[1000];int i = 0, j = 0;que[i++] = root;while(i > j){if(que[j]){que[i++] = que[j]->l;que[i++] = que[j]->r;printf("%c", que[j]->data);if(que[j]->l == NULL && que[j]->r == NULL)leaves++;}j++;} } /*void cengxu(Tree *root)//STL {Tree *temp;queue<Tree *>q;q.push(root);while(!q.empty()){temp = q.front();q.pop();if(temp){if(!temp->l && !temp->r)leaves++;printf("%c", temp->data);if(temp->l)q.push(temp->l);if(temp->r)q.push(temp->r);}} } */ int depth_bintree(Tree *root) {int de = 0;if(root){int left_depth = depth_bintree(root->l);int right_depth = depth_bintree(root->r);de = left_depth > right_depth ? left_depth + 1 : right_depth + 1;}return de; } int main() {while(~scanf("%s", pre)){cnt = 0;leaves = 0;Tree *root = creat();preoreder(root);printf("\n");midoreder(root);printf("\n");posoreder(root);printf("\n");cengxu(root);printf("\n");printf("%d\n", depth_bintree(root));printf("%d\n", leaves);}return 0; }

總結(jié)

以上是生活随笔為你收集整理的二叉树(前序遍历序列、中序遍历序列、后序遍历序列、层次遍历序列、深度、叶子数)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。