二叉树

#include <iostream>
#include <string>
#include "stdlib.h"
using namespace std;


typedef struct BiNode
{
  char data;
  struct BiNode *lchild;
  struct BiNode *rchild;
}BiNode,*BiTree;


//采用分治法根据前序和后序序列构建二叉树
//1)取先序遍历序列的第一个值,用该值构造根结点,,然后在中序遍历序列中查找与该元素相等的值,这样就可以把序列分为三部分:左子树(如果有)、根结点和右子树(如果有)。
//
//2)将两个序列都分成三部分,这样就分别形成了根结点的左子树和右子树的先序遍历和后序遍历的序列。
//
//3)重复1)和2)步骤,直至所有结点都处理完就可以完整构成一颗二叉树了。


void Create_BiTree(BiTree&t, string presequence,string insequence)
{
  //it is leaf
  if (presequence.length()==0)
  {
    t=NULL;
    return ;
  }
  //root
  char rootNode=presequence[0];
  //root location in inorder
  int index=insequence.find(rootNode);
  //left child sequence
  string lchild_insequence=insequence.substr(0,index);
  //right chlid sequence
  string rchild_insequence=insequence.substr(index+1);
  //left child length
  int lchild_length=lchild_insequence.length();
  //right child length
  int rchild_length=rchild_insequence.length();
  //left child presequence
  string lchild_presequence=presequence.substr(1,lchild_length);
  //right child presequence
  string rchild_presequence=presequence.substr(1+lchild_length);


  t=(BiTree)malloc(sizeof(BiNode));
  if (t!=NULL)
  {
    t->data=rootNode;
    Create_BiTree(t->lchild,lchild_presequence,lchild_insequence);
    Create_BiTree(t->rchild,rchild_presequence,rchild_insequence);
  }
}


void  PreOrder(BiTree&t) //前序遍历
{
  if (t!=NULL)
  {
    cout<<t->data;
    PreOrder(t->lchild);
    PreOrder(t->rchild);
  }
}


void InOrder(BiTree&t) //中序遍历
{
  if (t!=NULL)
  {
    InOrder(t->lchild);
    cout<<t->data;
    InOrder(t->rchild);
  }
}

void PostOrder(BiTree&t){ //后序遍历
if (t!=NULL)
  {
    PostOrder(t->lchild);
    PostOrder(t->rchild);
    cout<<t->data;
  }
}

int Depth(BiTree T) { //树的深度
	int n,m;
	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 main()
{
    BiTree a;
	int height,num;
	string presequence="ABDFGCEH";
   string insequence="BFDGACEH";
	Create_BiTree(a,presequence,insequence);
	cout<<"按先序遍历法输出该二叉树的元素为:\n";
	PreOrder(a);
    cout<<"\n按中序遍历法输出该二叉树的元素为:\n";
	InOrder(a);
	cout<<"\n按后序遍历法输出该二叉树的元素为:\n";
	PostOrder(a);
	height=Depth(a);
	num=NodeCount(a);
	cout<<"\n该二叉树深度为:";
	cout<<height<<endl;
	cout<<"该二叉树结点数为:";
	cout<<num;
	return 0;

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值