#include<iostream>
#include<string>
#include<queue>
using namespace std;
struct node {
char elem;
node *pL;
node*pR;
};
int NUM;
const int MAX = 100;
char a[MAX];
node* findNode(node*p,char elem) {
if (p->elem == elem) return p;
else {
node*tmp;
if (p->pL != NULL){
tmp=findNode(p->pL, elem);
if (tmp != NULL) return tmp;
}
if (p->pR != NULL) {
tmp = findNode(p->pR, elem);
if (tmp != NULL)return tmp;
}
}
return NULL;
}
node* creatTree() {
node*root = (node*)malloc(sizeof(node));
cout << "输入节点数:";
cin >> NUM; int num = NUM;
if (NUM) { cout << "输入根节点:"; cin >> root->elem; root->pL = NULL; root->pR = NULL; }
while (--num) {
char father; int connect=0; node*pF;
node*p= (node*)malloc(sizeof(node));p->pL = p->pR = NULL;
cout << "输入父节点,子节点,关系(0左子节点,1右子节点):";
cin >> father >> p->elem >> connect;
pF = findNode(root, father);
if (pF != NULL) {
if (connect) {
if (pF->pR != NULL) {
cout << "更新右子节点" << (pF->pR)->elem << endl; num++;
}
pF->pR = p;
}
else {
if (pF->pL != NULL) {
cout << "更新原左子节点" << (pF->pL)->elem << endl;num++;
}
pF->pL = p;
}
}
else {
cout << "父节点不存在,请重新输入";
num++;
}
}
return root;
}
void preorder(node*p) {
cout << p->elem;
if (p->pL != NULL)preorder(p->pL);
if (p->pR != NULL)preorder(p->pR);
}
void inorder(node*p) {
if (p->pL != NULL)inorder(p->pL);
cout << p->elem;
if (p->pR != NULL)inorder(p->pR);
}
void postorder(node*p) {
if (p->pL != NULL)postorder(p->pL);
if (p->pR != NULL)postorder(p->pR);
cout << p->elem;
}
queue<node *> s;
void level(node*p) {
s.push(p);
while (s.size()) {
node* tmp = s.front();
cout << tmp->elem;
s.pop();
if (tmp->pL != NULL)s.push(tmp->pL);
if (tmp->pR != NULL)s.push(tmp->pR);
}
}
void levelC(node* p,int i) {
a[i] = p->elem;
if (p->pL != NULL)levelC(p->pL, 2 * i+1);
if(p->pR!=NULL)levelC(p->pR, 2 * i+2);
}
void printLevel(node*p) {
int i = 0;
levelC(p, i);
cout << "层序递归: ";
for (int i = 0, j = 0; i < NUM;j++) {
if (a[j]) { cout << a[j]; i++; }
}
}
int main() {
memset(a, 0, sizeof(a));
node*root = creatTree();
string f[4] = { "前序递归:","中序递归:","后序递归:" ,"层序队列:"};
for (int i = 0; i <4 ; ++i){
cout << endl << f[i];
if(!i)preorder(root);
else if (i == 1)inorder(root);
else if(i==2) postorder(root);
else {
level(root);
cout << endl;
printLevel(root); }
}
return 0;
}
二叉树的构建与遍历(前序中序后序层序的递归与非递归实现)
最新推荐文章于 2023-01-24 16:11:34 发布