二叉树的链式存储与递归遍历

#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;
}

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值