闲着整理出来。
#include <stdio.h>
#include <string.h>
#include <iostream>
using namespace std;
struct Node {
int date;
Node *lChild, *rChild;
};
int n;
Node *create(int i) { // 建树
Node *root;
root = new Node();
root->date = i;
if (2*i <= n)
root->lChild = create(2*i);
else root->lChild = NULL;
if (2*i+1 <= n)
root->rChild = create(2*i+1);
else root->rChild = NULL;
return root;
}
void pre_order(Node *root) { // 先序遍历
if (root == NULL)
return;
printf("%d ", root->date);
pre_order(root->lChild);
pre_order(root->rChild);
}
void in_order(Node *root) { // 中序遍历
if (root == NULL)
return;
in_order(root->lChild);
printf("%d ", root->date);
in_order(root->rChild);
}
void post_order(Node *root) { // 后序遍历
if (root == NULL)
return;
post_order(root->lChild);
post_order(root->rChild);
printf("%d ", root->date);
}
int main() {
while(cin >> n) {
Node *root = create(1);
pre_order(root);
cout << endl;
in_order(root);
cout << endl;
post_order(root);
cout << endl;
}
return 0;
}
浙公网安备 33010602011771号