建立二叉搜索樹


建立二叉搜索樹還是比較容易的,一般是給定無序或者先序遍歷的數列,根據數字大小來安排位置。

/*示例中的二叉樹采用鏈式存儲*/
#include<iostream>
#include<queue>
using namespace std;
typedef struct node* BT;
struct node{
    int data=0;
    BT LChild=NULL,RChild=NULL;
};

BT BuildBST(BT t,int num);//建立二叉搜索樹 
void LevelTraversal(BT t);//層序遍歷,用來驗證BST是否創建成功 

int main()
{
    int N;
    scanf("%d",&N);
    BT tree=NULL;
    for(int i=0;i<N;i++){
        int tmp;
        scanf("%d",&tmp);
        tree=BuildBST(tree,tmp);
    }
    LevelTraversal(tree);
    return 0;
}

BT BuildBST(BT t,int num)
{
    if(t==NULL){
        t=new node();
        t->data=num;
    }
    else{
        if(num<t->data)
            t->LChild=BuildBST(t->LChild,num);
    else
            t->RChild=BuildBST(t->RChild,num);
    }
    return t;
}

void LevelTraversal(BT t)
{
    if(t!=NULL){
        queue<BT> Q;
        Q.push(t);
        while(!Q.empty()){
            BT parent=Q.front();
            printf("%d ",parent->data);
            Q.pop();
            if(parent->LChild)
               Q.push(parent->LChild);
            if(parent->RChild)
               Q.push(parent->RChild);
        }
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM