递归建立二叉查找树(BST)以及递归求树的高度

1. BST

Time Limit: 2000MS Memory Limit: 65536K

Description

给出一个整数序列,请按照顺序建立二叉查找树(BST),然后输出这颗二叉树的高度。

例:输入顺序为37244232740242120。对应的二叉查找树如下所示。

    输出的高度为:4

输入格式:

首先输入整数N,表示N种测试情况。接下来是每种测试情况的输入数据。

每种测试情况有一行,即整数序列。

输出格式:

每种测试情况对应一行输出树的高度。

输入示例:

2

37,24,42,32,7,40,2,42,120

120,42,7,2,32,42,24,37,40

输出示例:

4

6

 

 

代码如下:

#include<iostream>
#include<string>
using namespace std;

class BinNodeptr{
public:
    int it;
    BinNodeptr* Left;
    BinNodeptr* Right;
public:
    BinNodeptr(){
        Left=Right=NULL;
    }
    BinNodeptr(int value,BinNodeptr* l=NULL,BinNodeptr* r=NULL){
        Left=l;
        Right=r;
        it=value;
    }

    ~BinNodeptr(){}
    int& val(){
        return it;
    }
    void setVal(const int value){
        it=value;
    }
    BinNodeptr* left()const{
        return Left;
    }
    BinNodeptr* right()const{
        return Right;
    }
    void setLeft(BinNodeptr* node=NULL){
        Left=node;
    }
    void setRight(BinNodeptr* node=NULL){
        Right=node;
    }
    bool isleaf(){
        return (Left==NULL)&&(Right==NULL);
    }




};
class BST:public BinNodeptr{
public:
    BinNodeptr* root;
    int nodecount;
    int height;
public:
    BST(){
        root=NULL;
    
        nodecount=0;
        height=0;
    }
    ~BST(){}
    BinNodeptr* insert(BinNodeptr*& root,BinNodeptr* node){
        if(root==NULL){
            root=node;
            return root;
        }
        else{
            if(node->val()<root->val()&&root->left()==NULL){root->setLeft(node);return root;}
            if(node->val()>=root->val()&&root->right()==NULL){root->setRight(node);return root;}
            if(node->val()<root->val()&&root->left()!=NULL)insert(root->Left,node);
            if(node->val()>=root->val()&&root->right()!=NULL)insert(root->Right,node);
        }


    }
    int max(int m,int n){
        if(m>=n)return m;
        return n;
    }
    int bstheight(BinNodeptr* root){
        if(root==NULL)return 0;
        
        return 1+max(bstheight(root->Left),bstheight(root->Right));
    }

    BinNodeptr* getRoot(){
        
        return root;
    }


};
int main(){
    int n;
    cin>>n;
    int value;
    char divide;
    BST* mybst=new BST();
    while(n--){
        mybst->root=NULL;
        //mybst->setRoot();
        divide='\0';
        while(divide!='\n'){
            cin>>value;
            cin.get(divide);
            
            mybst->insert(mybst->root,new BinNodeptr(value));

            
        }
        cout<<mybst->bstheight(mybst->root)<<endl;
    }
}

 

    原文作者:二叉查找树
    原文地址: https://blog.csdn.net/cs_dota/article/details/8171837
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞