首页 > 其他 > 详细

二叉树的非递归前序遍历

时间:2015-01-08 17:58:55      阅读:328      评论:0      收藏:0      [点我收藏+]

//好久不用C++许多语法细节都忘记了...费了九牛二虎之力还搞的那么复杂,Anyway,下午把前序遍历给写出来了,还是有点成绩的。。。

#include<iostream>
#include<stack>
using namespace std;
typedef int dataType;
typedef struct BiTree
{
	dataType data;
	BiTree *lchild;
	BiTree *rchild;
}BiTree,*treePoint;
treePoint CreateTree(treePoint root)
{
	dataType data;
	cin>>data;
	if(data==-1)
	{
		return NULL;
	}
	root=new  BiTree;
	root->data=data;
	root->lchild=CreateTree(root->lchild);
	root->rchild=CreateTree(root->rchild);
	return root;
}
void PreOrderTraverse(treePoint root)
{
	if(root==NULL)
		cout<<"hello world!"<<endl;
	BiTree *bt=NULL;
	if(root==NULL)
		return;
	cout<<root->data<<endl;
	stack<BiTree *>st;
	st.push(root);
	while(!st.empty())
	{
		bt=st.top();
		while(bt->lchild!=NULL)
		{
			st.push(bt->lchild);
			cout<<bt->lchild->data<<endl;
			bt=bt->lchild;
		}
		//st.pop();
		bt=st.top();
		st.pop();
		if(bt->rchild!=NULL)
		{
			st.push(bt->rchild);
			cout<<bt->rchild->data<<endl;
			continue;
		}else
		{
			while(!st.empty())
			{
				bt=st.top();
				st.pop();
				if(bt->rchild!=NULL)
				{
					st.push(bt->rchild);
					cout<<bt->rchild->data<<endl;
					break;
				}
			}
			
		}
	}
}
int main()
{
	treePoint root=NULL;
	root=CreateTree(root);
	PreOrderTraverse(root);
	system("pause");
	return 0;
}


二叉树的非递归前序遍历

原文:http://blog.csdn.net/mnmlist/article/details/42526817

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!