二叉树遍历算法实现

二叉树的三种常见遍历方式:先根遍历、中根遍历、后根遍历。

二叉树节点结构体如下:

struct node //根节点结构体
{
char name;
Node* parent;
Node* left_child;
Node* right_child;
};

定义三个遍历函数:

void pre_order(Node* Tree) //先根遍历
{
if(Tree) //如果不是空节点
{
cout<<Tree->name<<endl;//根,左,右
pre_order(Tree->left_child);
pre_order(Tree->right_child);
}
}


void in_order(Node* Tree) //中根遍历
{
if(Tree) //如果不是空节点
{
in_order(Tree->left_child);//左,根,右
cout<<Tree->name<<endl;
in_order(Tree->right_child);
}
}


void post_order(Node* Tree) //后根遍历
{
if(Tree) //如果不是空节点
{
post_order(Tree->left_child);//左,右,根
post_order(Tree->right_child);
cout<<Tree->name<<endl;
}
}


全部代码以及测试结果:

#include<iostream>
using namespace std;

struct node 	//根节点结构体
{
	char name;
	Node* parent;
	Node* left_child;
	Node* right_child;	
};



void pre_order(Node* Tree)	//先根遍历
{
	if(Tree)	//如果不是空节点
	{
		cout<<Tree->name<<endl;		//根,左,右
		pre_order(Tree->left_child);
		pre_order(Tree->right_child);
	}
}

void in_order(Node* Tree)	//中根遍历
{
	if(Tree)	//如果不是空节点
	{
		in_order(Tree->left_child);		//左,根,右
		 cout<<Tree->name<<endl;
		 in_order(Tree->right_child);
	}
}

void post_order(Node* Tree)		//后根遍历
{
	if(Tree)	//如果不是空节点
	{
		post_order(Tree->left_child);		//左,右,根
		post_order(Tree->right_child);
		cout<<Tree->name<<endl;
	}
}

int main()
{
	Node node_A;
	node_A.name = 'A';
	node_A.parent = NULL;

	Node node_B;
	node_B.name = 'B';
	node_F.parent = NULL;
	node_F.left_child = NULL;
	node_F.right_child = NULL;

	Node node_C;
	node_C.name = 'C';
	node_C.parent = NULL;
	node_C.left_child = NULL;
	node_C.right_child = NULL;

	Node node_D;
	node_D.name = 'D';
	node_D.parent = NULL;
	node_D.left_child = NULL;
	node_D.right_child = NULL;

	Node node_E;
	node_E.name = 'E';
	node_E.parent = NULL;
	node_E.left_child = NULL;
	node_E.right_child = NULL;

	Node node_F;
	node_F.name = 'F';
	node_F.parent = NULL;
	node_F.left_child = NULL;
	node_F.right_child = NULL;

	node_A.parent = NULL;
	node_A.left_child = &node_B;
	node_A.right_child = &node_C;

	node_B.parent = &node_A;
	node_B.left_child = &node_D;
	node_B.right_child = &node_E;

	node_C.parent = &node_A;
	node_C.left_child = NULL;
	node_C.right_child = NULL;

	node_D.parent = &node_B;
	node_D.left_child = &node_F;
	node_D.right_child = NULL;

	node_E.parent = &node_B;
	node_E.left_child = NULL;
	node_E.right_child = NULL;

	node_F.parent = &node_D;
	node_F.left_child = NULL;
	node_F.right_child = NULL;

	pre_order(&node_A);
	cout<<endl;
	in_order(&node_A);
	cout<<endl;
	post_order(&node_A);
	


	return 0;
}

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值