二叉樹非遞歸遍歷

#include <iostream>
#include <stack>
#include <queue>

using namespace std;

struct Node 
{
	char data;

	Node *lchild, *rchild;
};

void Create(Node* &root)
{
	char ch;

	cin >> ch;

	if (ch == '#')
	{
		root = NULL;
	}
	else
	{
		root = new Node;

		root->data = ch;

		Create(root->lchild);
		Create(root->rchild);
	}
}

void PreOrder(Node *root)   //前序和中序
{
	stack<Node*> s;

	while(!s.empty() || root)  
	{
		while(root)                        //左子樹入棧
		{
			//cout << root->data << " ";  //前序

			s.push(root);

			root = root->lchild;
		}

		//cout << s.top()->data << " "; //中序

		root = s.top()->rchild;			

		s.pop();	
	}
}

void LevelOrder(Node *root)  //層序遍歷
{
	queue<Node*> q;

	if (root != NULL)
	{
		q.push(root);

		while(!q.empty())
		{
			root = q.front();

			cout << root->data << " ";

			q.pop();

			if (root->lchild)
			{
				q.push(root->lchild);
			}

			if (root->rchild)
			{
				q.push(root->rchild);
			}
		}
	}
}

void PostOrder(Node *root)   //後序
{
	stack<Node*> s;

	Node *p, *q;
	int flag;

	while(!s.empty() || root)
	{
		while(root)
		{
			s.push(root);

			root = root->lchild;
		}

		flag = 1;

		p = NULL;

		while(flag && !s.empty())
		{
			q = s.top();
			
			if (q->rchild == p)
			{
				cout << q->data << " ";

				s.pop();

				p = q;    //記錄訪問過節點
			}
			else
			{
				root = q->rchild;

				flag = 0;
			}
		}

	
	}
}

void Release(Node *root)
{
	if (root != NULL)
	{
		Release(root->lchild);
		Release(root->rchild);

		delete root;
	}
}

int main()
{
	Node *root = NULL;

	Create(root);

	PreOrder(root);
	LevelOrder(root);
	PostOrder(root);

	Release(root);

	return 0;
}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章