二叉树
1、二叉树的前序中序后序层次遍历
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<queue>
using namespace std;
char s[2050];
typedef struct node{
char data;
node *left,*right;
}node,*tree;
queue<tree>q;
void init(tree *l){
(*l)=NULL;
}
void build(tree *l,int *c){//输入为二叉树的前序遍历序列,空用#代替
(*c)++;
if(s[*c]=='#'){
(*l)=NULL;
return;
}
(*l)=(node *)malloc(sizeof(node));
(*l)->data=s[*c];
build(&((*l)->left),c);
build(&((*l)->right),c);
}
void printfx(tree l){//前序遍历
if(l==NULL){
return;
}
else{
printf("%c",l->data);
printfx(l->left);
printfx(l->right);
return;
}
}
void printfz(tree l){//中序 遍历
if(l==NULL){
return;
}
else{
printfz(l->left);
printf("%c",l->data);
printfz(l->right);
return;
}
}
void printfh(tree l){//后序遍历
if(l==NULL){
return;
}
else{
printfh(l->left);
printfh(l->right);
printf("%c",l->data);
return ;
}
}
void printfc(tree l){//层次遍历
while(!q.empty()){
q.pop();
}
if(l!=NULL){
q.push(l);
}
while(!q.empty()){
node *neww;
neww=q.front();
q.pop();
printf("%c",neww->data);
if(neww->left!=NULL)
q.push(neww->left);
if(neww->right!=NULL)
q.push(neww->right);
}
return;
}
int main(){
tree l;
int c;
while(gets(s)){
c=-1;
init(&l);
build(&l,&c);
printfx(l);
printf(" ");
printfz(l);
printf(" ");
printfh(l);
printf(" ");
printfc(l);
printf("\n");
}
return 0;
}
输入
ab#f##cd##e##
输出
abfcde bfadce fbdeca abcfde
下面是之前做的笔记
2、求二叉树的深度
int getdeep(tree l,int deep){
if(l==NULL){
return deep;
}
else{
deep++;
return max(getdeep(l->left,deep),getdeep(l->right,deep));
}
}
3、求二叉树的宽度
queue<tree>q;
int getwidth(tree l){
int maxx=1;
if(l==NULL){
return 0;
}
else{
q.push(l);
int temp1=1,temp2=0;
while(!q.empty()){
while(temp1--){
node *neww;
neww=q.front();
if(neww->left!=NULL){
q.push(neww->left);
temp2++;
}
if(neww->right!=NULL){
q.push(neww->right);
temp2++;
}
q.pop();
}
temp1=temp2;
temp2=0;
if(temp1>maxx){
maxx=temp1;
}
}
}
return maxx;
}
4、判断二叉树是否为完全二叉树
按层遍历二叉树,从每层的左边向右边依次遍历;
如果当前节点有右孩子,但没有左孩子,直接返回false;
如果当前节点并不是左右孩子都有,那之后的节点应都为叶节点,否则返回false;
int judge(tree l){
while(!q.empty()){
q.pop();
}
int flag=0;
if(l==NULL){
return 1;//是二叉树
}
else{
q.push(l);
while(!q.empty()){
node *neww;
neww=q.front();
if((flag&&(neww->left!=NULL||neww->right!=NULL))||(neww->left==NULL&&neww->right!=NULL)){
return 0;
}
if(neww->left!=NULL){
q.push(neww->left);
}
if(neww->right!=NULL){
q.push(neww->right);
}
if(neww->left!=NULL&&neww->right==NULL||neww->left==NULL&&neww->right==NULL){
flag=1;//这个结点之后的结点应该都为叶子结点
}
q.pop();
}
}
return 1;
}