合并两个二叉搜索树

9 篇文章 0 订阅

如何合并两个二叉搜索树?

How would you merge two binary search tree's ?

假设二叉搜索树分别有m和n个元素。通过单独遍历每个BST,能得到两个已排序的数组,大小分别为m和n,时间复杂度分别为O(m) 和O(n)。将它们合并为一个数组,时间复杂度为O(m+n).重新建立平衡二叉树花费O(m+n)时间。

Lets say BSTs are of m and n elements respectively. By doing individual in order traversal of each BST we can get two sorted linked list of m and n elements which will be achieved in O(m) and O(n). merging these to form an array is of O(m+n). Now creating a balanced BST out of this array will again be O(m+n), we can use the simple technique shown.

#include <stdio.h>
struct BST
{
	BST(int a):data(a){}
	int data;
	BST* left;
	BST* right;
};
BST* sortedArrToBST(int arr[],int start,int end)
{
	if (start>end)
	{
		return NULL;
	}
	int midd = (start+end)/2;
	BST* root = new BST(arr[midd]);
	root->left = sortedArrToBST(arr,start,midd-1);
	root->right = sortedArrToBST(arr,midd+1,end);
	return root;
}





  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值