二叉树的表达以及遍历算法(挑战程序设计竞赛第八章)

#include<iostream>

using namespace std;

const int N= 100010;	//定义
const int nil = -1;		//定义一个标记

struct Node{
	int parent,left,right;
};						//定义一个结构体树,双亲结点,左孩子,右孩子
Node L[N];				//结构体数组
int D[N],H[N],n;		//深度数组,高度数组

/*  parnet=父节点
	sibling = 兄弟结点
	degree = 子节点个数
	depth = 结点深度
	height = 结点高
	root =树根	internal = 内部结点		leaf =	叶子节点
	输入:
	9
	0 1 4
	1 2 3
	2 -1 -1
	3 -1 -1
	4 5 8
	5 6 7
	6 -1 -1
	7 -1 -1
	8 -1 -1
*/

void Preorder(int u)
{	
	if(u==nil)
		return;
	cout << u;
	Preorder(L[u].left);
	Preorder(L[u].right);
}
void Inorder(int u)
{
	if(u==nil)
		return;
	Inorder(L[u].left);
	cout << u;
	Inorder(L[u].right);
}
void Postorder(int u)
{
	if(u==nil)
		return;
	Postorder(L[u].left);
	Postorder(L[u].right);
	cout << u;
}
void Depth(int u,int d)			//深度递归求结点的深度
{
	if(u == nil)	return;
	D[u] = d;
	Depth(L[u].left,d+1);
	Depth(L[u].right,d+1);
}

int Height(int u)				//递归求结点的高度
{
	int h1=0,h2=0;
	if(L[u].left != nil)	h1 = Height(L[u].left)+1;
	if(L[u].right != nil)	h2 = Height(L[u].right)+1;
	return H[u] = (h1>h2?h1:h2);
}

int sibling(int u)				//求兄弟结点  L[L[u].parent].left为此结点的双亲结点下的另一个孩子结点
{
	if(L[u].parent == nil)	return nil;
	if(L[L[u].parent].left != u && L[L[u].parent].left != nil)	return L[L[u].parent].left;
	if(L[L[u].parent].right != u && L[L[u].parent].right !=nil)	return L[L[u].parent].right;
	return nil;
}

void print(int u)				//打印这个二叉树的情况
{
	cout << "Node " << u << ":";
	cout << "parent =" << L[u].parent << ",";
	cout << "sibling =" << sibling(u) <<",";
	cout << "degree =";
	int cnt =0;
	if(L[u].left!=nil)	cnt++;
	if(L[u].right!=nil)	cnt++;
	cout <<cnt <<",";
	cout <<"depth =" << D[u] <<",";
	cout << "height =" <<	H[u] <<",";
	if(L[u].parent ==nil)	cout << "root" <<endl;
	else if(L[u].left == nil && L[u].right == nil)	cout << "leaf" <<endl;
	else	cout << "internal node" <<endl;
}
int main()
{
	int i,l,r,root;
	cin >>n;
	for(i=0;i<n;i++)	L[i].left = L[i].parent = L[i].right = nil;			//对所有结点都进行初始化,设为-1
	for(i=0;i<n;i++)
	{
		int x;
		cin >>x >> l>> r;
		L[x].left =l;
		L[x].right=r;
		if(L[x].left!=nil)	L[l].parent =x;
		if(L[x].right!=nil)	L[r].parent =x;
	}
	for(i=0;i<n;i++)
		if(L[i].parent == nil)	root=i;			//求这个二叉树的根节点
	
	Depth(root,0);
	Height(0);
	for(i=0;i<n;i++)	print(i);
	cout <<endl;
	cout << "Preorder" <<endl;
	Preorder(root) ;
	cout <<endl;
	cout << "Inorder" <<endl;
	Inorder(root);
	cout <<endl;
	cout <<"Post" <<endl;
	Postorder(root);
	cout <<endl;
	
	return 0;

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值