建立二叉查找树c++

#include<iostream>

using namespace std;


struct BinaryNode
{
  int elem;
  BinaryNode *left;
  BinaryNode * right;
  BinaryNode( int d,BinaryNode *l=NULL, BinaryNode *r=NULL):elem(d),left(l),right(r){};
};




BinaryNode* insertion(BinaryNode *root , int x)
{
    BinaryNode *p=new BinaryNode(x,NULL,NULL);

    if(root == NULL){
        root = p;
    }
    else if(x < root->elem){
        root->left = insertion(root->left, x);
    }
    else if(x > root->elem){
        root->right = insertion(root->right, x);
    }
    return root;
}

BinaryNode* creatBinarySearchTree(int len, int ptr[])
{
    BinaryNode *p=new BinaryNode(ptr[0],NULL,NULL);

	for (int i = 1; i < len; i++)
	{

		insertion(p , ptr[i]);
	}

	return p;
}

void print(BinaryNode *root)
{
    if(root!=NULL)
    {
        cout<<root->elem<<endl;

        if(root->left)print(root->left);
        if(root->right)print(root->right);
    }
}

int main()
{
    int arr[8]={1,3,4,6,54,8,9,34};

    BinaryNode *p=creatBinarySearchTree(8,arr);

    print(p);

}

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