二叉查找樹的核心約定只有一句:左子樹所有結點值小於根,右子樹所有結點值大於根。依此插入,中序遍歷的結果天然有序。下面按輸入數組構造一棵。
#include <iostream>
using namespace std;
/*二叉查找樹結構*/
typedef struct BSTree
{
int node_value;
struct BSTree * left;
struct BSTree * right;
} Tree;
/*****構造二叉查找樹**********************************************/
void CreateBSTree(Tree * root, int node_value);
Tree * CreateBSTree(int * array_list, int array_length);
void Print(Tree* root);
/*****************************************************************/
int main(int argc, char * argv)
{
Tree * root = NULL;
int list[] = {5, 3, 4, 9, 1, 7, 11};
root = CreateBSTree(list, 7);
std::cout << "Cearte BSTree." << std::endl;
Print(root);
return 0;
}
/*生成二叉查找樹*/
Tree * CreateBSTree(int * array_list, int array_length)
{
if (array_length <= 0)
{
return false;
}
Tree * root = NULL;
root = new BSTree();
root->left = NULL;
root->right = NULL;
root->node_value = array_list[0];
for (int i = 1; i < array_length; i++)
{
CreateBSTree(root, array_list[i]);
}
return root;
}
void CreateBSTree(Tree * root, int node_value)
{
if (root == NULL)
{
return;
}
if (root->node_value > node_value)
{
if (root->left == NULL)
{
Tree * node = new Tree();
node->left = NULL;
node->right = NULL;
node->node_value = node_value;
root->left = node;
}
else
{
CreateBSTree(root->left, node_value);
}
}
else
{
if (root->right == NULL)
{
Tree * node = new Tree();
node->left = NULL;
node->right = NULL;
node->node_value = node_value;
root->right = node;
}
else
{
CreateBSTree(root->right, node_value);
}
}
}
/*中序排序輸出二叉查找樹*/
void Print(Tree* root)
{
if (root == NULL)
{
return;
}
Print(root->left);
std::cout << root->node_value << "\t";
Print(root->right);
}
兩個同名函數構成重載:一個接收數組指針與長度,負責用首元素建根、其餘元素逐个插入;另一個接收根指針與待插入值,沿比較結果一路向左或向右遞歸,直到找到空位為止。
以 list 為例,5 為根,3 進左,4 再從 3 的右側落位,9 進右,以此類推。中序遍歷的輸出為 1 3 4 5 7 9 11,正好有序——這也是檢驗 BST 是否建對的最快方法。
兩處值得留意:array_length <= 0 時返回 false 是指向 Tree* 的函數返回布爾值,語義上不嚴謹,應改為返回 NULL;另外 new 出來的結點在程序結束前未釋放,正式代碼需補上析構邏輯。