二叉树的前序遍历 非递归的几种方法

第一种:

template<class T>  void BinaryTree<T>::PreOrderWithoutRecusion
(BinaryTreeNode<T>* root)
//非递归前序遍历二叉树或其子树
{
	using std::stack;	//使用STL中的stack
	stack<BinaryTreeNode<T>* > aStack;
	BinaryTreeNode<T>* pointer=root;
	aStack.push(NULL); // 栈底监视哨
	while(pointer){  // 或者!aStack.empty()
		Visit(pointer->value());    //访问当前结点
		if (pointer->rightchild() != NULL)   //右孩子入栈
			aStack.push(pointer->rightchild());
		if (pointer->leftchild() != NULL)
			pointer = pointer->leftchild();   //左路下降
		else  { //左子树访问完毕,转向访问右子树
			pointer=aStack.top();	
			aStack.pop();  //栈顶元素退栈 }
		}
	}
}

第二种:(数据结构书上的)

	stack< BinaryTreeNode<T>* > aStack;
	BinaryTreeNode<T>* pointer;
	if(root == NULL)
	{
		return;
	}
	pointer = root;
	Visit(pointer);
	aStack.push(pointer);
	while(!aStack.empty())
	{
		while(pointer = aStack.top())
		{	
			Visit(pointer);
			aStack.push(pointer->leftchild());
		}
		aStock.pop();//空指针退栈
		if(!aStack.empty())
		{
			pointer = aStack.top();
			aStack.pop();
			aStack.push(pointer->rightchild());
		}
	}
第三种:(北大张铭老师ppt)

stack<BinaryTreeNode<T>* > aStack;
BinaryTreeNode<T>* pointer=root;
while(!aStack.empty()||pointer){
if(pointer){
//访问当前结点
Visit(pointer);    
//当前结点地址入栈
aStack.push(pointer);
//当前链接结构指向左孩子
pointer=pointer->leftchild();
}
else {//左子树访问完毕,转向访问右子树
pointer=aStack.top();
aStack.pop();     //栈顶元素退栈 
//当前链接结构指向右孩子
pointer=pointer->rightchild();

} //end while


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值