二叉树Tree的构造和遍历,图的结构(C++)

本文介绍了如何使用C++实现二叉搜索树的数据结构,包括节点创建、插入、搜索、查找最小值、计算树的高度,以及广度优先搜索(BFS)和深度优先搜索(DFS)。同时提及了网络爬虫中图的两种表示方法:邻接矩阵和邻接表。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include<bits/stdc++.h>
using namespace std;
//BST二叉数
struct node{
    int data;
    node* l;
    node* r;
};
node* newnode(int x){
    node* tp = new node;
    tp->data=x;
    tp->l=NULL;
    tp->r=NULL;
    return tp;
}
node* insert(node* p, int x){
    if(p==NULL) p=newnode(x);
    else if(x <= p->data){
        p->l = insert(p->l, x);
    }else{
        p->r = insert(p->r, x);
    }
    return p;
}
bool serch(node* p, int x){
    if(p==NULL) return 0;
    else if(p->data == x) return 1;
    else if(x<=p->data) return serch(p->l, x);
    else return serch(p->r, x);
}
int findmin(node* p){
    if(p==NULL){
        cout<<"wa"<<endl; return -1;
    }else{
        while(p->l != NULL){
            p = p->l;
        }
    }
    return p->data;
}
int findheight(node* p){//树的最大高度,最远根节点到root边数;
    if(p==NULL) return -1;
    else return max(findheight(p->l), findheight(p->r))+1;
}
//遍历算法
void bfs(node* p){
    if(p==NULL) return;
    queue<node* > q;
    q.push(p);
    while(!q.empty()){
        node* tp =q.front();
        cout<<tp->data<<' ';
        if(tp->l!=NULL) q.push(tp->l);
        if(tp->r!=NULL) q.push(tp->r);
        q.pop();
    }
    return;
}
void dfs(node* p){
    //if(p==NULL) return;
    cout<<p->data<<' ';
    if(p->l !=NULL)
        dfs(p->l);
    if(p->r !=NULL)
        dfs(p->r);
}
int main(){
    node* a=NULL;
    a = insert(a, 50);
    a = insert(a, 40);
    a = insert(a, 60);
    dfs(a);
    return 0;
}
#include<bits/stdc++.h>
using namespace std;
//网络爬虫==图的遍历
//有向图,权重图

// class edge{
//     string st;
//     string ed;
//     int w;
// };
//邻接矩阵表示//图稀疏时用
// string s[10];
// int graph[10][10];

//邻接表表示,用vector或者bst
string id[10];//把图中点转为id使用
struct node{
    int next;
    int w;
};
vector<node> a[10];//邻接表存每个点指向
vector<node>* s[10];//每个点对应的邻接表

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值