您的位置:首页 > 其它

Data Structure Binary Tree: Morris traversal for Preorder

2014-03-29 07:02 441 查看
http://www.geeksforgeeks.org/morris-traversal-for-preorder/

#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) {
while (root) {
if (root->left == NULL) {
cout << root->data << " ";
root = root->right;
}
else {
node* cur = root->left;
while (cur->right && cur->right != root) cur = cur->right;
if (cur->right == NULL) {
cout << root->data << " ";
cur->right = root;
root = root->left;
}
else {
cur->right = NULL;
root = root->right;
}
}
}
}

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);
root->left->left->left = new node(8);
root->left->left->right = new node(9);
root->left->right->left = new node(10);
root->left->right->right = new node(11);
prints(root);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: