# 二叉树遍历之非递归算法

## 1、先序遍历（非递归算法）

void preOrderIter(struct node *root)
{
if (root == NULL) return;
stack<struct node *> s;
s.push(root);
while (!s.empty()) {
struct node *nd = s.top();
cout << nd->data << " ";
s.pop();
if (nd->right != NULL)
s.push(nd->right);
if (nd->left != NULL)
s.push(nd->left);
}
cout << endl;
}


void preOrderIter2(struct node *root)
{
stack<struct node *> s;
while (root != NULL || !s.empty()) {
if (root != NULL) {
cout << root->data << " "; //访问结点并入栈
s.push(root);
root = root->left;         //访问左子树
} else {
root = s.top();            //回溯至父亲结点
s.pop();
root = root->right;        //访问右子树
}
}
cout << endl;
}


## 2、中序遍历（非递归算法）

void inOrderIter(struct node *root)
{
stack<struct node *> s;
while (root != NULL || !s.empty()) {
if (root != NULL) {
s.push(root);
root = root->left;
}
else {
root = s.top();
cout << root->data << " ";  //访问完左子树后才访问根结点
s.pop();
root = root->right;        //访问右子树
}
}
cout << endl;
}


## 3、后序遍历（非递归算法）

1. Push根结点到第一个栈s中。
2. 从第一个栈s中Pop出一个结点，并将其Push到第二个栈output中。
3. 然后Push结点的左孩子和右孩子到第一个栈s中。
4. 重复过程2和3直到栈s为空。
5. 完成后，所有结点已经Push到栈output中，且按照后序遍历的顺序存放，直接全部Pop出来即是二叉树后序遍历结果。

void postOrderIter(struct node *root)
{
if (!root) return;
stack<struct node*> s, output;
s.push(root);
while (!s.empty()) {
struct node *curr = s.top();
output.push(curr);
s.pop();
if (curr->left)
s.push(curr->left);
if (curr->right)
s.push(curr->right);
}

while (!output.empty()) {
cout << output.top()->data << " ";
output.pop();
}
cout << endl;
}


## 4、层序遍历（非递归算法）

### 方法一：使用两个队列

void levelOrderIter(struct node* root)
{
if (!root) return;
queue<struct node *> currentLevel, nextLevel;
currentLevel.push(root);
while (!currentLevel.empty()) {
struct node *currNode = currentLevel.front();
currentLevel.pop();
if (currNode) {
cout << currNode->data << " ";
nextLevel.push(currNode->left);
nextLevel.push(currNode->right);
}
if (currentLevel.empty()) {
cout << endl;
swap(currentLevel, nextLevel);
}
}
}

void swap(queue<struct node *> &curr, queue<struct node*> &next)
{
while (!next.empty()) {
struct node *nd = next.front();
next.pop();
curr.push(nd);
}
}


### 方法二：使用一个队列

void levelOrderIter2(struct node *root)
{
if (!root) return;
queue<struct node*> nodesQueue;
int nodesInCurrentLevel = 1;
int nodesInNextLevel = 0;
nodesQueue.push(root);
while (!nodesQueue.empty()) {
struct node *currNode = nodesQueue.front();
nodesQueue.pop();
nodesInCurrentLevel--;
if (currNode) {
cout << currNode->data << " ";
nodesQueue.push(currNode->left);
nodesQueue.push(currNode->right);
nodesInNextLevel += 2;
}
if (nodesInCurrentLevel == 0) {
cout << endl;
nodesInCurrentLevel = nodesInNextLevel;
nodesInNextLevel = 0;
}
}
}