# 二叉树前、中、后序遍历（递归与非递归）

struct TreeNode
{
int val;
TreeNode *left;
TreeNode *right;
};

TreeNode *createTree()
{
TreeNode *root;
int x;
scanf("%d", &x);
if (x == -1)
root = NULL;
else
{
root = (TreeNode *)malloc(sizeof(TreeNode));
root->val = x;
root->left = createTree();
root->right = createTree();
}
return root;
}

void PreOrder(TreeNode *root)
{
if (root == 0)
return;
printf("%d", root->val);
PreOrder(root->left);
PreOrder(root->right);
}
void InOrder(TreeNode *root)
{
if (root == 0)
return;
InOrder(root->left);
printf("%d", root->val);
InOrder(root->right);
}
void PostOrder(TreeNode *root)
{
if (root == 0)
return;
PostOrder(root->left);
PostOrder(root->right);
printf("%d", root->val);
}


void PreOrder_Nonrecursive(TreeNode *root)
{
if  (root == 0)
return;
TreeNode *p = root;
stack<TreeNode *> S;
while (!s.empty() || p)
{
while (p)
{
cout << p->val << endl;
S.push(p);
p = p->left;
}
p = S.top();
S.pop();
p = p->right;
}
}

void InOrder_Nonrecursive(TreeNode *root)
{
if (root == 0)
return;
TreeNode *p = root;
stack<TreeNode *> S;
while (!S.empty() || p)
{
while (p)
{
S.push(p);
p = p->left;
}
p = S.top();
S.pop();
cout << p->val << endl;
p = p->right;
}
}

void PostOrder_Nonrecursive1(TreeNode *root)
{
if (root == 0)
return;
TreeNode *p = root;
stack<TreeNode *> S;
TreeNode *previsited = NULL;
while (!S.empty() || p)
{
while (p)
{
S.push(p);
p = p->left;
}
p = S.top();
if (p->right == previsited || p->right == NULL)
{
cout << p->val << endl;
previsited = p;
S.pop();
p = NULL;
}
else
p = p->right;
}
} 

void PostOrder_Dualstack(TreeNode *root)
{
if (root == 0)
return;
TreeNode *p = root;
stack<TreeNode *> S1;
stack<TreeNode *> S2;
S1.push(p);
while (!S1.empty())
{
p = S1.top();
S1.pop();
S2.push(p);
if (p->left) S1.push(p->left);
if (p->right) S2.push(p->right);
}
while (!S2.empty())
{
p = S2.top();
S2.pop();
cout << p->val << endl;
}
}

---------------------------------------------------------------------------------------------------------------------------------------------------------------------

TreeNode* create(int pre[], int in[], int l1,int r1, int l2, int r2)
{
if (l1 > r1) return NULL;
TreeNode *node = new TreeNode(pre[l1];
int l = l2;
int i = 0;
for (; l <= r2; l++, i++)
{
if (pre[l1] == in[l])
break;
}
node->left = create(pre, in, l1+1, l1+i, l2, l-1);
node->right = create(pre, in, l1+i+1, r1, l+1, r2);
return node;
}


#### 数据结构——二叉树的递归与非递归遍历（先序，中序，后序）

2017-12-18 20:32:09

#### 二叉树的定义和递归实现

2017-05-05 21:43:23

#### 1058FBI<二叉树，递归，后序遍历>

2016-05-01 09:00:04

#### 二叉树的后序遍历（递归）

2013-10-20 12:26:09

#### 【c++】构建一棵简单的二叉树

2016-10-16 15:58:21

#### 二叉树的前中后序遍历，递归和非递归方式

2017-04-10 19:34:35

#### 多叉树（二叉树）的递归与非递归的后序遍历

2018-01-25 21:08:55

#### 二叉树前中后序遍历（递归）

2016-04-26 09:36:20

#### 二叉树前中后遍历

2017-03-25 12:48:35

#### 二叉树的递归和非递归前、中、后序遍历

2017-05-06 11:27:17