二叉树的先序建立、遍历、镜像、节点数、深度的具体代码实现

二叉树的先序建立、遍历、镜像、节点数、深度的具体代码实现




实现代码(VC6.0编译通过):


#include <iostream>
#include <queue>
using namespace std;

//二叉树节点定义
class Node
{
public:
	char value;
	Node* lchild;
	Node* rchild;
};

//先序创建二叉树    输入先序遍历的字符顺序 例如  ab###
void CreateTree(Node* &tree)
{
	char ch;
	scanf("%c",&ch);

	if(ch=='#')tree=NULL;
	else
	{
		tree=new Node();
		tree->value=ch;
		CreateTree(tree->lchild);//递归创建左子树
		CreateTree(tree->rchild);//递归创建右子树
	}
}

//先序遍历
void preorder(Node* tree)
{
	if(tree!=NULL)
	{
		cout<<tree->value;
		preorder(tree->lchild);
		preorder(tree->rchild);
	}
}

//中序遍历
void midorder(Node* tree)
{
	if(tree!=NULL)
	{
		preorder(tree->lchild);
		cout<<tree->value;		
		preorder(tree->rchild);
	}
}

//后序遍历
void latorder(Node* tree)
{
	if(tree!=NULL)
	{
		preorder(tree->lchild);			
		preorder(tree->rchild);
		cout<<tree->value;	
	}
}

//层序遍历
void grade(Node* tree)
{
	queue<Node*> myque;
	//根节点不为空,先进队列
	if(tree!=NULL)
	{
		myque.push(tree);
	}
	//如果队列不空,则继续
	while(!myque.empty())
	{
		Node* temp=myque.front();
		myque.pop();
		//左子树不空,则进队列
		if(temp->lchild)myque.push(temp->lchild);
		//右子树不空,则进队列
		if(temp->rchild)myque.push(temp->rchild);
		cout<<temp->value<<" ";
	}
}

//二叉树的镜像
void mirror(Node* tree)
{
	if(tree!=NULL)
	{
		Node* temp;
		temp=tree->lchild;
		tree->lchild=tree->rchild;
		tree->rchild=temp;
		//交换左子树
		mirror(tree->lchild);
		//交换右子树
		mirror(tree->rchild);
	}
}

//二叉树节点数
int count(Node* tree)
{
	if(tree==NULL)return 0;
	return count(tree->lchild)+count(tree->rchild)+1;
}

//二叉树深度
int deep(Node* tree)
{
	if(tree==NULL)return 0;
	return deep(tree->lchild)>deep(tree->rchild)?deep(tree->lchild)+1:deep(tree->rchild)+1;
}
int main()
{
	Node* root;
	CreateTree(root);
	cout<<"先序遍历:";
	preorder(root);
	cout<<endl;
	cout<<"中序遍历:";
	midorder(root);
	cout<<endl;
	cout<<"后序遍历:";
	latorder(root);

	cout<<endl;
	cout<<"层序遍历:";
	grade(root);

	cout<<endl;
	cout<<"镜像:";
	mirror(root);
	preorder(root);
	
	cout<<endl;
	cout<<"节点数:";
	cout<<count(root);

	cout<<endl;
	cout<<"树深度:";
	cout<<deep(root);

	return 0;
}



输出:




更多内容请访问 IT部落格(http://www.itbuluoge.com)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值