您的位置:首页 > 其它

Data Structure Binary Tree: Iterative Postorder Traversal

2014-03-29 10:16 387 查看
http://www.geeksforgeeks.org/iterative-postorder-traversal-using-stack/

#include <iostream>
#include <vector>
#include <algorithm>
#include <queue>
#include <stack>
#include <string>
#include <fstream>
#include <map>
using namespace std;

struct node {
int data;
struct node *left, *right;
node() : data(0), left(NULL), right(NULL) { }
node(int d) : data(d), left(NULL), right(NULL) { }
};

void prints(node *root) {
if (!root) return;
stack<node*> S;
do {
while (root) {
if (root->right) S.push(root->right);
S.push(root);
root = root->left;
}
root = S.top();
S.pop();
if (root->right && !S.empty() && root->right == S.top()) {
S.pop();
S.push(root);
root = root->right;
}
else {
cout << root->data << " ";
root = NULL;
}
} while (!S.empty());
}

int main() {
node *root = new node(1);
root->left = new node(2);
root->right = new node(3);
root->left->left = new node(4);
root->left->right = new node(5);
root->right->left = new node(6);
root->right->right = new node(7);
prints(root);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: