数据结构之二叉树的遍历

先序遍历:

void preorder(node* root)
{
	if(root != NULL)
	{
		Visit(root);		//假设Visit()函数已经定义;
		preorder(root->lchild);
		preorder(root->rchild);
	}
}

中序遍历:



void inorder(node* root)
{
	if(root != NULL)
	{
		inorder(root->lchild);
		Visit(root);
		inorder(root->rchild);
	}
}

后续遍历:

void postorder(node* root)
{
	if(root != NULL)
	{
		postorder(root->lchild);
		postorder(root->rchild);
		Visit(root);
	}
}

层次遍历:

void level(node* root)
{
	int front,rear;
	node *que[maxsize];			//首先定义一个循环队列,用来记录将要访问层次上的节点;
	front = rear = 0;
	node *p;
	if(root != NULL)
	{
		rear = (rear+1) % maxsize;		//rear指针往后移一位;
		que[rear] = root;				//根节点入队;
		while(front != rear)
		{
			front = (front+1)%maxsize;
			p = que[front];			//队头节点出队
			Visit(p);				//访问队头节点
			if(p->lchild != NULL)	//如果左子树不空,则左子树根节点入队
			{
				rear = (rear+1) % maxsize;
				que[rear] = p->lchild;
			}
			if(p->rchild != NULL)	//如果右子树不空,则右子树根节点入队
			{
				rear = (rear+1) % maxsize;
				que[rear] = p->rchild;
			}
		}
		
	}
]

下面是关于C++代码的扩展(考研初试用不上,因为不能用STL库):

void level(node* root)
{
	if(root == NULL)	return{};
	vector<vector<int>> ans;
	queue<node*> q;
	q.push(root);
	while(!q.empty())
	{
		vector<int> BFS;
		node* now = q.front();
		int count = q.size();
		while(count--)
		{
			q.pop();
			if(now->lchild != NULL)
				q.push(now->lchild);
			if(now->rchild != NULL)
				q.push(now->rchild);
			BFS.push_back(now->data);
		}
		ans.push_back(BFS);
	}
	return ans;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值