生活随笔
收集整理的這篇文章主要介紹了
二叉树(前序遍历序列、中序遍历序列、后序遍历序列、层次遍历序列、深度、叶子数)
小編覺得挺不錯的,現(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
++;}
}
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)容還不錯,歡迎將生活随笔推薦給好友。