#include <iostream>
#include <stack>
#include <queue>
using namespace std;
typedef struct node {
int data;
node *left;
node *right;
node() {
data = 0;
left = NULL;
right = NULL;
}
} *bt;
void pre(bt root) {
if (NULL == root)
return ;
cout << root->data << " ";
pre(root->left);
pre(root->right);
}
void pre2(bt root) {
stack<bt> s;
bt p = root;
while (NULL != p || !s.empty()) {
while (NULL != p) {
cout << p->data << " ";
s.push(p);
p = p->left;
}
if (!s.empty()) {
p = s.top();
s.pop();
p = p->right;
}
}
}
void in(bt root) {
if (NULL == root)
return ;
in(root->left);
cout << root->data << " ";
in(root->right);
}
void in2(bt root) {
stack<bt> s;
bt p = root;
while (NULL != p || !s.empty()) {
while (NULL != p) {
s.push(p);
p = p->left;
}
if (!s.empty()) {
p = s.top();
cout << p->data << " ";
s.pop();
p = p->right;
}
}
}
void post(bt root) {
if (NULL == root)
return ;
post(root->left);
post(root->right);
cout << root->data << " ";
}
void post2(bt root) {
stack<bt> s;
bt cur = root;
bt pre = NULL;
s.push(cur);
while (!s.empty()) {
cur = s.top();
if ((cur->left == NULL && cur->right == NULL) ||
(pre != NULL && (pre == cur->left || pre == cur->right))) {
cout << cur->data << " ";
s.pop();
pre = cur;
}
else {
if (cur->right != NULL)
s.push(cur->right);
if (cur->left != NULL)
s.push(cur->left);
}
}
}
void layer(bt root) {
if (NULL == root)
return ;
queue<bt> q;
q.push(root);
while (!q.empty()) {
bt temp = q.front();
q.pop();
cout << temp->data << " ";
if (NULL != temp->left)
q.push(temp->left);
if (NULL != temp->right)
q.push(temp->right);
}
}
int maxDepth(bt root) {
if (root == NULL)
return 0;
int left = 1;
int right = 1;
left += maxDepth(root->left);
right += maxDepth(root->right);
return ((left > right) ? left : right);
}
int main() {
bt root = new node;
root->data = 1;
bt p1 = new node;
p1->data = 2;
bt p2 = new node;
p2->data = 3;
bt p3 = new node;
p3->data = 4;
bt p4 = new node;
p4->data = 5;
bt p5 = new node;
p5->data = 6;
root->left = p1;
root->right = p2;
p1->left = p3;
p1->right = p4;
p2->left = p5;
/*
1
2 3
4 5 6
*/
cout << "Preorder: ";
pre(root);
cout << endl;
cout << "Preorder2: ";
pre2(root);
cout << endl;
cout << "Inorder: ";
in(root);
cout << endl;
cout << "Inorder2: ";
in2(root);
cout << endl;
cout << "Postorder: ";
post(root);
cout << endl;
cout << "Postorder: ";
post2(root);
cout << endl;
cout << "Layerorder: ";
layer(root);
cout << endl;
cout << "The depth of tree: " << maxDepth(root) << endl;
}
树的遍历
最新推荐文章于 2023-03-14 17:04:32 发布