c语言 BST 二叉搜索树实现

Modified on: Sun, 24 May 2020 23:56:21 +0800 热度: 2,006 度
#include <iostream>
#include <cstdlib>
#include <ctime>

using namespace std;

typedef struct Node{
    int Value;
    struct Node* Left;
    struct Node* Right;
}Node,*Tree;

Tree Insert(Tree tree,int value)
{
    if(tree==NULL)
    {
        tree = (Tree)malloc(sizeof(Node));
        tree->Value=value;
        tree->Left=NULL;
        tree->Right=NULL;
        return tree;
    }
    if(tree->Value>value)
    {
        tree->Left=Insert(tree->Left,value);
    }else
    {
        tree->Right=Insert(tree->Right,value);    
    }
    return tree;
}

void inOrderTraverse(Tree tree)
{
    if(tree==NULL) return;
    
    inOrderTraverse(tree->Left);
    cout<<tree->Value<<" ";
    inOrderTraverse(tree->Right);
}

int main()
{
    Tree tree=NULL;
    int T=10;
    srand((unsigned int)time(0));
    while(T--)
        tree=Insert(tree,rand()%100);
    inOrderTraverse(tree);
    return 0;
} 

添加新评论