# 二叉树的DFS迭代遍历

·  阅读 1353

### 1. 前序遍历的迭代实现

``````void preOrder(TreeNode* p){
if(p == NULL)
return;
cout << p->val <<endl;
preOrder(p->left);
preOrder(p->right);
}

``````     1
/   \
2     3
/ \   / \
4   5 6   7

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

### 2. 中序遍历的迭代实现

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

### 3. 后序遍历的迭代实现

``````void afterOrder(TreeNode* root) {
if (root== NULL)
return;
stack<TreeNode*> s;
vector<TreeNode*> v;
s.push(root);
TreeNode* p = NULL;
while (!s.empty()) {
p = s.top();
bool flag1 = false;
bool flag2 = false;

if (p->left == NULL)
flag1 = true;
if (p->right == NULL)
flag2 = true;
if (!flag1) {
auto it = v.begin();
for (; it != v.end(); it++) {
if (*it == p->left)
break;
}
if (it != v.end()) {
flag1 = true;
}
}
if (!flag2) {
auto it = v.begin();
for (; it != v.end(); it++) {
if (*it == p->right)
break;
}
if (it != v.end()) {
flag2 = true;
}
}
if (flag1 == true && flag2 == true) {
v.push_back(s.top());
s.pop();
}
else if (flag1 == false) {
s.push(p->left);
}
else if (flag1 == true && flag2 == false) {
s.push(p->right);
}
}
for (auto p : v) {
cout << p->val << endl;
}
}