1. 程式人生 > >C++ 二叉排序樹

C++ 二叉排序樹

#include <bits/stdc++.h>
#define MaxSize 100
#define ArrayLen(array) sizeof(array)/sizeof(array[0])
/*
* Created by HarvestWu on 2018/07/24.
*/
using namespace std;


//定義二叉樹結構
typedef struct BTNode
{
	int key;
	struct BTNode *lchild;
	struct BTNode *rchild;
} BTNode;

//二叉排序樹關鍵字插入
int BSTInsert(BTNode *&bt, int key)
{
	if (bt==NULL)
	{
		bt = (BTNode*)malloc(sizeof(BTNode));
		bt->lchild = bt->rchild = NULL;
		bt->key = key;
		return 1;
	}
	else
	{
		if (key == bt->key)
			return 0;
		else if (key < bt->key)
			return BSTInsert(bt->lchild, key);
		else return BSTInsert(bt->rchild, key);
	}
}

//建立二叉排序樹
void CreateBST(BTNode *&bt, int key[], int n)
{
	bt = NULL;
	for (int i = 0; i < n; ++i)
		BSTInsert(bt, key[i]);
}

//二叉排序樹中序遍歷
void inOrder(BTNode *bt)
{
	if (bt != NULL)
	{
		inOrder(bt->lchild);
		cout << bt->key << " ";
		inOrder(bt->rchild);
	}
}

int main()
{
	BTNode *bt;
	int key[] = { 1, 5, 7, 6, 3, 4, 8, 9, 2 };
	int n = ArrayLen(key);
	CreateBST(bt, key, n);
	inOrder(bt);
	return 0;
}