#include<iostream>
using namespace std;
struct node {
node *lson;
int data;
node *rson;
/
node *father;
};
void insert(node *a,node *b,int dad) {
if (dad==a->data) {
if(a->lson==NULL) {a->lson=b;}
else {
if (a->rson==NULL) {a->rson=b;}
else {cout<<"该父节点已满!"<<endl;return;}
}
b->father=a;
cout<<"插入成功!"<<endl;
}
else {
if (a->lson!=NULL) {insert(a->lson,b,dad);}
if (a->rson!=NULL) {insert(a->rson,b,dad);}
}
}
//先序遍历
void visit(node *t) {
cout<<t->data<<endl;
if (t->lson!=NULL) {visit(t->lson);}
if (t->rson!=NULL) {visit(t->rson);}
}
/*
中序遍历
void visit(node *t) {
if (t->lson!=NULL) {visit(t->lson);}
cout<<t->data<<endl;
if (t->rson!=NULL) {visit(t->rson);}
}
后序遍历
void visit(node *t) {
if (t->lson!=NULL) {visit(t->lson);}
if (t->rson!=NULL) {visit(t->rson);}
cout<<t->data<<endl;
}
*/
void find(int x,node *t) {
if (x==t->data) {
cout<<x;
while (t->father!=NULL) {
cout<<"-->"<<t->father->data;
t=t->father;
}
cout<<endl;
}
else {
if (t->lson!=NULL) {find(x,t->lson);}
if (t->rson!=NULL) {find(x,t->rson);}
}
}
int main() {
node head;
head.father=NULL;head.lson=NULL;head.rson=NULL;
cout<<"请输入根节点:";
cin>>head.data;
while (1) {
cout<<"请输入节点及它的父节点,输入-1 -1结束:"<<endl;
int x,dad;
cin>>x>>dad;
if (x==-1&&dad==-1) {break;}
node *box=new node;
box->data=x;box->father=NULL;box->lson=NULL;box->rson=NULL;
insert(&head,box,dad);
}
visit(&head);
while (1) {
cout<<"请输入要查询的节点,输入-1结束:";
int x;
cin>>x;
if (x==-1) {break;}
find(x,&head);
}
return 0;
}
二叉树的链式存储与递归遍历
于 2024-01-21 11:08:01 首次发布