我是靠谱客的博主 平淡嚓茶,这篇文章主要介绍二叉树的小程序,现在分享给大家,希望可以做个参考。

没事做,写了个二叉树的小程序,供初学者看看

#include<iostream>
using namespace std;
#define defeated NULL

struct Tree
{
	char ele;
	Tree *lchild;
	Tree *rchild;
};
Tree *create()
{
	char ch;
	cin>>ch;
	if(ch=='#')
	{
		return NULL;
	}
	else
	{
		Tree *root=(Tree*)malloc(sizeof(Tree));
		root->ele=ch;
		root->lchild=create();
			root->rchild=create();
			return root;
	}
}

void visit(Tree *t)
{
	cout<<t->ele<<" ";
}
void preOrder(Tree * t )
{
	if(t!=NULL)
	{
		visit(t);
		preOrder(t->lchild);
		preOrder(t->rchild);
	}
}
int size(Tree *t)
{
	if(t==NULL)
 return 0;
	else return 1+size(t->lchild)+size(t->rchild);

}
int sizeOfLeaves(Tree *t)
{
	if(t==NULL)  return 0;
	else if(t->lchild==NULL&&t->rchild==NULL) return 1;
	else return sizeOfLeaves(t->lchild)+sizeOfLeaves(t->rchild);
}
int depth(Tree *t)
{
	int h1,h2,h;
	if(t!=NULL)
	{
		h1=depth(t->lchild);
		h2=depth(t->rchild);
		h=h1>h2?h1:h2;
		return h+1;
	}
	return 0;
}

int main()
{
 cout<<"---t Weclome to binary Tree!-----tn";
 Tree *p;
 p=create();
 cout<<"Select the function please! n";
 cout<<"1 遍历这棵树n";
 cout<<"2 查找节点个数n";
 cout<<"3 叶子结点个数n";
 cout<<"4 树的深度n";
 int sizeOfTree=size(p);
 int leaves=sizeOfLeaves(p);
 int d=depth(p);
 int k=0;
 cout<<"begin scan& use?(1 for yes)n";
 cin>>k;
 while(k)
 {
 int option;
 cin>>option;
 switch(option)
 {
 case 1: preOrder(p);
	 cout<<'n';
	 break;
 case 2: cout<<"结点个数为: "<<sizeOfTree<<'n';break;
 case 3: cout<<"叶子结点个数为: "<<leaves<<'n';break;
 case 4: cout<<"树的深度为:  "<<d<<'n';break;
 default: cout<<"Unknown Error!";
 }
 cout<<"继续或结束?(1 for yes)n";
 cin>>k;
 if(k==1) system("cls");
 cout<<"Select the function please! n";
 cout<<"1 遍历这棵树n";
 cout<<"2 查找节点个数n";
 cout<<"3 叶子结点个数n";
 cout<<"4 树的深度n";

 }
 return 0;
}

最后

以上就是平淡嚓茶最近收集整理的关于二叉树的小程序的全部内容,更多相关二叉树内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(52)

评论列表共有 0 条评论

立即
投稿
返回
顶部