zoukankan      html  css  js  c++  java
  • 建立二叉搜索树

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

    /*示例中的二叉树采用链式存储*/
    #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);
            }
        }
    }
  • 相关阅读:
    升级centos6.5系统的gcc为4.8.5的简易步骤
    赛车比赛(洛谷U4566)
    月考(cogs 1176)
    xth的旅行(codevs 1450)
    魔法禁书目录2:回家(codevs 3024)
    交换
    牛的旅行(洛谷 1522)
    长途旅行
    序列问题
    正确答案
  • 原文地址:https://www.cnblogs.com/yinhao-ing/p/10610230.html
Copyright © 2011-2022 走看看