我想实现一个算法,将已排序的数组插入到二叉搜索树中,但我不希望最终得到一个只增长到一边的树。
你有什么想法吗?
感谢。
答案 0 :(得分:11)
这应该给你一个平衡的树(在O(n)中):
类似Java的代码:
TreeNode sortedArrayToBST(int arr[], int start, int end) {
if (start > end) return null;
// same as (start+end)/2, avoids overflow.
int mid = start + (end - start) / 2;
TreeNode node = new TreeNode(arr[mid]);
node.left = sortedArrayToBST(arr, start, mid-1);
node.right = sortedArrayToBST(arr, mid+1, end);
return node;
}
TreeNode sortedArrayToBST(int arr[]) {
return sortedArrayToBST(arr, 0, arr.length-1);
}
代码来自here。
答案 1 :(得分:3)
public class SortedArrayToBST {
public TreeNode sortedArrayToBST(int[] num) {
if (num == null) {
return null;
}
return buildBST(num, 0, num.length - 1);
}
private TreeNode buildBST(int[] num, int start, int end) {
if (start > end) {
return null;
}
int mid = start + (end - start) / 2;
TreeNode root = new TreeNode(num[mid]);
TreeNode left = buildBST(num, start, mid - 1);
TreeNode right = buildBST(num, mid + 1, end);
root.left = left;
root.right = right;
return root;
}
}
答案 2 :(得分:0)
以伪随机顺序插入它们,如下所示:
#include <stdio.h>
int array[] = {1,2,3,4,5,6,7,8,9,10};
#define COUNT 10
#define STEP 7 /* must be relatively prime wrt COUNT */
#define START 5 /* not important */
int main(void)
{
unsigned idx;
idx=START;
while(1) {
printf("[%u] = %u\n", idx, array[idx] );
// do_insert(array[idx] );
idx = (idx + STEP ) % COUNT;
if (idx == START) break;
}
return 0;
}