目录

                  1.复制二叉树

2.求二叉树的深度

3.求二叉树的结点数

4.求二叉树的叶子结点数

5.完整代码及运行如下:


1.复制二叉树

void Copy(BiTree S,BiTree &NewS){
    if(S==NULL){
        NewS=NULL;
        return;
    }
    else{
        NewS=new Tree;
        NewS->data=S->data;
        Copy(S->lchild,NewS->lchild);
        Copy(S->rchild,NewS->rchild);
    }
}

2.求二叉树的深度

int Depth(BiTree T){
    int m,n;
    if(T==NULL){
        return 0;
    }
    else{
        m=Depth(T->lchild);
        n=Depth(T->rchild);
        if(m>n){
            return (m+1);
        }
        else{
            return (n+1);
        }
    }
}

3.求二叉树的结点数

int NodeCount(BiTree T){
    if(T==NULL){
        return 0;
    }
    else{
        return NodeCount(T->lchild)+NodeCount(T->rchild)+1;
    }
}

4.求二叉树的叶子结点数

int LeafCount(BiTree T){
    if(T==NULL){
        return 0;
    }
    if(T->lchild==NULL&&T->rchild==NULL){
        return 1;
    }
    else{
        return LeafCount(T->lchild)+LeafCount(T->rchild);
    }
}

5.完整代码及运行如下:

//二叉树遍历算法的应用--复制二叉树
#include<stdio.h>
#include<stdlib.h>
typedef struct Tree{
	int data;
	struct Tree *lchild;
	struct Tree *rchild;
}Tree,*BiTree;
BiTree CreateTree(); 
void Copy(BiTree S,BiTree &NewS);
void xianxu(BiTree T);
int Depth(BiTree T);
int NodeCount(BiTree T);
int LeafCount(BiTree T);
int main(){
	BiTree S;
	BiTree NewS;
	S= CreateTree();
	
	Copy(S,NewS);
	xianxu(S);
	printf("\n");
	printf("这棵数复制后:");
	xianxu(NewS);
	printf("\n"); 
	int depth=Depth(S);
	printf("这棵数的深度:%d",depth);
	printf("\n");
	int nodecount=NodeCount(S);
	printf("这棵树的所有结点数:%d",nodecount);
	printf("\n");
	int leafcount=LeafCount(S);
	printf("这棵树的叶子结点数:%d",leafcount);
	return 0;
} 
BiTree CreateTree(){
	int data;
	int temp;
	BiTree T;
	scanf("%d",&data);
	temp=getchar();
	
	if(data==-1){
		return NULL;
	}
	T=(BiTree)malloc(sizeof(Tree));
	T->data=data;
	T->lchild=CreateTree();
	T->rchild=CreateTree();
	return T;
}
void Copy(BiTree S,BiTree &NewS){
	if(S==NULL){
		NewS=NULL;
		return;
	}
	else{
		NewS=new Tree;
		NewS->data=S->data;
		Copy(S->lchild,NewS->lchild);
		Copy(S->rchild,NewS->rchild);
	}
}
void xianxu(BiTree T){
	if(T==NULL){
		return;
	}
	printf("%d ",T->data);
	xianxu(T->lchild);
	xianxu(T->rchild);
}
int Depth(BiTree T){
	int m,n;
	if(T==NULL){
		return 0;
	}
	else{
		m=Depth(T->lchild);
		n=Depth(T->rchild);
		if(m>n){
			return (m+1);
		}
		else{
			return (n+1);
		}
	}
}
int NodeCount(BiTree T){
	if(T==NULL){
		return 0;
	}
	else{
		return NodeCount(T->lchild)+NodeCount(T->rchild)+1;
	}
}
int LeafCount(BiTree T){
	if(T==NULL){
		return 0;
	}
	if(T->lchild==NULL&&T->rchild==NULL){
		return 1;
	}
	else{
		return LeafCount(T->lchild)+LeafCount(T->rchild);
	}
}

 

 

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐