二叉树遍历的递归和非递归实现

一、二叉树的先序遍历:首先访问跟节点,再依次访问它的左子树和右子树。

递归方法:

void preorder(node *root)
{
	if(NULL == root)
		return ;
	visit(root);
	preorder(root->leftchild);
	preorder(root->rightchild);
}


 

其非递归算法,利用C++STL中的stack(栈)实现。首先分析一个二叉树的前序递归算法的顺序。如下图的二叉树:其前序遍历为ABDCEFGH

其非递归的具体实现代码如下:

void preorder(node *root)
{
	if(NULL == root)
		return;
	stack<node*> node_stack;
	node *cur = root;
	while(cur!= NULL && !node_stack.empty())
	{
		while(cur!=NULL)
		{
			visit(cur);
			node_stack.push(cur);
			cur = cur->leftchild;
		}
		if(!node_stack.empty())
		{
			cur = node_stack.top();
			node_stack.pop();
			cur = cur ->rightchild;
		}
	}

}


 

二、二叉树的中序遍历:首先访问左子树,然后访问根结点,最后访问右子树。

         其递归算法如下:

void inorder(node *root)
	{
		if(NULL = root)
			return;
		inorder(root->leftchild);
		visit(root);l
		inorder(root->rightchild);
}


图中二叉树中序遍历的顺序为:BDAFEHGC;

也可以用栈来实现二叉树的中序遍历:
void inorder(node *root)
{
	if(root == NULL)
		return;
	stack<node*> node_stack;
	node cur = root;
	while(cur != NULL || !node_queue.empty())
	{
		while(cur != NULL)
		{
			node_stack.push(cur);
			cur = cur->leftchild;
		}
		if(!node_stack.empty())
		{
			cur = node_stack.top();
			visit(cur);
			node_stak.pop();
			cur = cur->rightchild;
		}
	}
}


 

三、后序遍历:先访问左子树,在访问右子树,最后访问根结点

         其递归实现为:

void postorder(node *root)
	{
		if(NULL == root)
			return;
		postorder(root->leftchild);
		postorder(root->rightchild);
		visit(root);
	}


 

对于上图中后序遍历结果为:DBFHGECA

 

void postorder(node *root)
{
	if(NULL == root)
		return;
	stack<node*> node_stack;
	node* cur = root;
	node *temp = NULL;
	while(cur != NULL || !node_stack.empty())
	{
		while(cur != NULL)
		{
			node_stack.push(cur);
			cur = cur->leftchild;
		}
		if(!node_stack.empty())
		{
			cur = node_stack.top();
			if( cur->rightchild == NULL || cur->rightchild == temp)
			{
				visit(cur);
				temp = cur->rightchild;
				node_stack.pop();
			cur = NULL;
			}
		else
			cur = cur->rightchild;
	    }
	}

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值