合并两个二叉搜索树
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.
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; }
相关文章推荐
- [编程题]合并两个排序的链表
- 两个有序数组的合并排序,Java代码实现,并去重复,考虑空间利用率问题
- 合并两个数组并去重
- JS 两个数组合并
- 【Ubuntu】用vim来合并两个文件的命令
- 将两个递增的有序链表合并为一个递增的有序链表
- 合并已经排序的两个数组,合并后也需要排序
- 《剑指offer》-合并两个排序的链表
- [PAT] 02-线性结构1 两个有序链表序列的合并
- Scala 之 合并两个map
- 02-线性结构1 两个有序链表序列的合并 (15分)
- 合并两个单调递增的链表,使得合并后的链表也是有序
- 视频编程作业-两个有序列表的合并
- Java SE - 使用Java合并两个图像的方法
- #21 合并排序后的两个链表
- 合并两个有序链表,合并后依然有序
- mysql合并 两个count语句一次性输出结果的方法
- 《剑指Offer》输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历的结果。如果是则输出Yes,否则输出No。假设输入的数组的任意两个数字都互不相同。
- .定义两个数组,首先把两个数组合并成一个新数组,然后把新数组中的所有元素逆序排列,需要实现的效果如图-2所示。
- 合并两个排序后的链表