1,分别写了先序遍历,中序遍历和后序遍历以及层次遍历的非递归算法!
- // 树的建立和遍历.cpp : 定义控制台应用程序的入口点。
- //
- #include "stdafx.h"
- #include <stack>
- #include <queue>
- #include <iostream>
- using namespace std;
- struct Node
- {
- int data;
- struct Node* left;
- struct Node* right;
- Node(int x):
- data(x),left(NULL),right(NULL){}
- };
- //按先序遍历建树
- Node* createTree()
- {
- int a;
- cin >> a;
- if (a == -1)
- {
- return NULL;
- }
- Node* root = new Node(a);
- root->left = createTree();
- root->right = createTree();
- return root;
- }
- //先序非递归遍历
- void preorder(Node* root)
- {
- if (root == NULL)
- {
- return;
- }
- stack<Node*> s;
- while (root)
- {
- cout << root->data << ' ';
- s.push(root);
- root = root->left;//走到最左孩子
- }
- while (!s.empty())
- {
- Node* temp = s.top();//取栈顶元素
- s.pop();//出栈
- temp = temp->right;//看有没有右孩子
- while (temp)
- {
- cout << temp->data << ' ';
- s.push(temp);
- temp = temp->left;
- }
- }
- cout << endl;
- }
- //中序遍历非递归算法
- void inorder(Node* root)
- {
- if (root == NULL)
- {
- return;
- }
- stack<Node*> s;
- while (root)
- {
- s.push(root);
- root = root->left;//进栈到最左孩子
- }
- while (!s.empty())
- {
- Node* temp = s.top();
- cout << temp->data << ' ';
- s.pop();//出栈,看右孩子
- temp = temp->right;
- while (temp)
- {
- s.push(temp);
- temp = temp->left;
- }
- }
- cout << endl;
- }
- //后序遍历非递归算法
- void postorder(Node* root)
- {
- if (root == NULL)
- {
- return;
- }
- stack<Node*> s;
- Node* previsited = NULL;//记录刚被访问的节点
- while (root)
- {
- s.push(root);
- root = root->left;
- }
- while (!s.empty())
- {
- Node* temp = s.top();
- if (temp->right == NULL || temp->right == previsited)
- {
- cout << temp->data << ' ';
- s.pop();
- previsited = temp;
- }
- else
- {
- temp = temp->right;//找到右孩子,
- while (temp)
- {
- s.push(temp);
- temp = temp->left;
- }
- }
- }
- cout << endl;
- }
- //层次遍历二叉树,按层次输出
- void leveltraver(Node* root)
- {
- if (root == NULL)
- {
- return;
- }
- queue<Node*> q;
- q.push(root);
- while (!q.empty())
- {
- int length = q.size();
- while (length--)
- {
- Node* temp = q.front();
- cout << temp->data << ' ';
- q.pop();
- if (temp->left != NULL)
- {
- q.push(temp->left);
- }
- if (temp->right != NULL)
- {
- q.push(temp->right);
- }
- }
- cout << endl;
- }
- cout << endl;
- }
- int _tmain(int argc, _TCHAR* argv[])
- {
- cout << "输入数据先序建树:" << endl;
- Node* root = createTree();
- cout << "先序遍历为:" << endl;
- preorder(root);
- cout << "中序遍历为:" << endl;
- inorder(root);
- cout << "后序遍历为:" << endl;
- postorder(root);
- cout << "层次遍历为:" << endl;
- leveltraver(root);
- system("pause");
- return 0;
- }
二叉树的三种基本遍历非递归算法都可以用栈来实现,共同的操作时从根开始入栈,一直到最左孩子为止。
不同的是在出栈前访问,还是在进栈到最左孩子后,出栈时访问,还是在访问时要加条件判断!!!