您的位置:首页 > 其它

合并两个二叉搜索树

2013-05-16 19:44 1846 查看
如何合并两个二叉搜索树?

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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: