建立二叉搜索树

建立二叉搜索树还是比较容易的,一般是给定无序或者先序遍历的数列,根据数字大小来安排位置。

/*示例中的二叉树采用链式存储*/
#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);
        }
    }
}
原文地址:https://www.cnblogs.com/yinhao-ing/p/10610230.html