搜索二叉树BST

任务

题目和解题方法来源:左神(左程云):深入解析字节跳动算法面试题与数据结构

用C++实现算法(原讲解为Java)。并通过随机新建BST获得BST的后序遍历数组判定两BST是否相等进行测试。

源代码于GitHub

题目

已知一个搜索二叉树后序遍历的数组posArr,请根据posArr,重建出整棵树返回新建树的头节点

思路

左边小 右边大 没有重复节点

key words

后序遍历的数组最后是二叉树的根节点,通过比较数值大小找到分界mid将左子树和右子树分开

最优解实现方式:由遍历寻找分界值mid改为用二分法寻找mid,时间复杂度由O(n2 )降至O(nlogn)

解题

BST结构体

struct bst
{
	int nodeData;
	struct bst* left;
	struct bst* right;
};

解题法1:遍历寻找分界值

bst* reconstructBst(bst* root, int* arr, int leftRange, int rightRange)
{
	if (leftRange > rightRange)
		return NULL;
	root = new bst;
	root->nodeData = arr[rightRange];
	//最末一个节点
	if (rightRange == leftRange )
	{
		root->left = NULL;
		root->right = NULL;
		return root;
	}
	int limit;
	//得到分界处的角标limit
	for (limit = rightRange-1; limit>-1; limit--)
	{
		if (arr[limit] < arr[rightRange])
			break;
	}
	//建左子树和右子树
	root->left = reconstructBst(root->left, arr, leftRange, limit);
	root->right = reconstructBst(root->right, arr, limit+1, rightRange-1);
	return root;
}

解题法2:二分法寻找分界值

//最优解:二分法得分界处角标
bst* reconstructBst2(bst* root, int* arr, int leftRange, int rightRange)
{
	if (leftRange > rightRange)
		return NULL;
	root = new bst;
	root->nodeData = arr[rightRange];
	//最末一个节点
	if (rightRange == leftRange)
	{
		root->left = NULL;
		root->right = NULL;
		return root;
	}
	//二分法找到分界处的角标mid
	int left = leftRange, right = rightRange - 1;
	int mid = left + ((right - left) >> 1); //二分
	for (; right>=left; )
	{
		if (arr[mid] > arr[rightRange])
		{
			right = mid - 1;
			mid = left + ((mid - left) >> 1);//落在前半部分
		}
		else
		{
			left = mid+1;
			mid = right - ((right - mid) >> 1);//落在后半部分
		}
	}
	int limit;
	if (arr[mid] < arr[rightRange])
		limit = mid;
	else
		limit = mid - 1;
	//建左子树和右子树
	root->left = reconstructBst(root->left, arr, leftRange, limit);
	root->right = reconstructBst(root->right, arr, limit + 1, rightRange - 1);
	return root;
}

测试

随机新建BST

首先利用rand()生成随机数组(rand()在stdlib.h中),再用随机数组建立BST

//生成随机数组
void generateRandArray(int*arr,int size)
{
	for (int i = 0; i < size; i++)
	{
		arr[i] = rand() % 5;
		//cout << arr[i];
	}
	//cout << endl;
}

将随机产生的数组传入创建BST

bst* generateBst(bst*root,int* arr, int size)
{
	for (int i = 0; i < size; i++)
	{
		root = putNode(root, arr[i]);
	}
	return root;
	//lastOrder(root);
}
bst* putNode(bst* node, int data)
{
	if (node == NULL)
	{
		node = new(bst);
		node->nodeData = data;
		node->left = NULL;
		node->right = NULL;
		return node;
	}
	if (data < node->nodeData)
		node->left = putNode(node->left, data);
	if (data > node->nodeData)
		node->right = putNode(node->right, data);
	return node;
}

回收分配内存

void recycle(bst* root)
{
	if (root->left == NULL && root->right == NULL)
	{
		delete root;
		return;
	}
	if(root->left!=NULL)
		recycle(root->left);
	if(root->right!=NULL)
		recycle(root->right);
	delete root;
	return;
}

后序遍历BST

//仅打印
void lastOrder(bst* root)
{
	if (root == NULL)
		return;
	lastOrder(root->left);
	lastOrder(root->right);
	cout << root->nodeData;
}
//结果保存至数组
void lastOrderSave(bst* root,int*posArr,int&size)
{
	if (root == NULL)
		return;
	lastOrderSave(root->left,posArr,size);
	lastOrderSave(root->right,posArr,size);
	//cout << root->nodeData;
	*(posArr+size)=(root->nodeData);
	size++;
}

判定两BST是否全等

bool sameBst(bst* root1, bst* root2)
{
	bool result;
	if (root1 == NULL || root2 == NULL)
	{
		if (root1 == NULL && root2 == NULL)
			return true;
		else
			return false;
	}
	result=sameBst(root1->left, root2->left)&&sameBst(root1->right, root2->right)&& root1->nodeData == root2->nodeData;
	return result;
}

main

#include"bst.h"
#include<ctime>
using namespace std;
#define DEBUG false//true//true
#define SOLUTION1 true//false//true
#define SOLUTION2 true//false
#define ARRMAXSIZE 500
int main(void)
{
                int batch = 50000;
		cout << "begin " << batch << " times test for solution 1:" << endl;
		start = clock();		//程序开始计时
		for (int i = 0; i < batch; i++)
		{
			//生成随机数组
			int size = 100;
			int arr[ARRMAXSIZE];
			generateRandArray(arr, size);
			//建搜索二叉树
			bst* root = NULL;
			root = generateBst(root, arr, size);
			//后序遍历二叉树结果保存至数组arr
			size = 0;
			lastOrderSave(root, arr, size);
			//由后序遍历数组arr重建搜索二叉树
			if (SOLUTION1)
			{
				bst* reconstruct = NULL;
				reconstruct = reconstructBst(reconstruct, arr, 0, size - 1);
				//比较二者是否相同,若不同,打印消息
				if (!sameBst(root, reconstruct))
					cout << "************11111**not same*****111111**********" << endl;
				recycle(reconstruct);
			}
                         //由最优解后序遍历数组arr重建搜索二叉树
                         if (SOLUTION2)
			{
				bst* reconstruct2 = NULL;
				reconstruct2 = reconstructBst2(reconstruct2, arr, 0, size - 1);
				//比较二者是否相同,若不同,打印消息
				if (!sameBst(root, reconstruct2))
					cout << "**********222222****not same*******222222******" << endl;
				recycle(reconstruct2);
			}
			recycle(root);
		}
    return 0;
}

Leave a comment

Your email address will not be published. Required fields are marked *