ds 二叉树最大距离

#include<iostream>
#include<cstring>
using namespace std;
class node{
    public:
        char v;
        node *l;
        node *r;
};
string s;
int i;
node* build(node* r){
    if(s[i]=='#'){
        i++;
        r=NULL;
    }
    else {
        r=new node;
        r->v=s[i++];
        r->l=build(r->l);
        r->r=build(r->r);
    }
    return r;

void print(node* root){
    cout<<root->v;
    if(root->l!=NULL) print(root->l);
    if(root->r!=NULL) print(root->r);
}

int lmax,rmax;
char lstr,rstr;
void lMax(node* root,int now){
    if(now>lmax) lmax=now,lstr=root->v;
    if(root->l!=NULL) lMax(root->l,now+1);
    if(root->r!=NULL) lMax(root->r,now+1);
}

void rMax(node* root,int now){
    if(now>rmax) rmax=now,rstr=root->v;
    if(root->l!=NULL) rMax(root->l,now+1);
    if(root->r!=NULL) rMax(root->r,now+1);
}

int Max(node* root){
    lmax=0;rmax=0;
        if(root->l==NULL) lmax=0,lstr=root->v;
        else lMax(root->l,1);
        if(root->r==NULL) rmax=0,rstr=root->v;
        else rMax(root->r,1);
        if(lmax==rmax&&lmax==0) return 0;
        else return lmax+rmax;
}
int AMax;
char Lstr,Rstr;
void dfs(node* root){
    int l=Max(root);
    if(l>AMax) {
        AMax=l;
        Lstr=lstr;
        Rstr=rstr;
    }
    if(root->l!=NULL) dfs(root->l);
    if(root->r!=NULL) dfs(root->r);
}

int main(){
    int t;
    cin>>t;
    while(t--){
        i=0;
        cin>>s;
        node *root=new node;
        root=build(root);
        AMax=0;
        dfs(root);
        if(AMax==0) cout<<"0:"<<endl;
        else cout<<AMax<<":"<<Lstr<<" "<<Rstr<<endl;
    }
    return 0;
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值