将排序后的数组插入二叉搜索树 [英] Insert sorted array into binary search tree
本文介绍了将排序后的数组插入二叉搜索树的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想实现一种算法,将排序的数组插入到二叉搜索树中,但我不希望以只向一侧生长的树结束.
I want to implement an algorithm that inserts sorted arrays into binary search trees but I don't want ending up with a tree that only grows to one side.
你有什么想法吗?
谢谢.
推荐答案
这应该会给你一个平衡的树(在 O(n) 中):
This should give you a balanced tree (in O(n)):
- 为数组中的中间元素构造一个节点并返回它
(这将是基本情况下的根). - 从数组左半部分的 1. 开始重复,将返回值分配给根的左子节点.
- 在数组的右半部分从 1. 开始重复,将返回值分配给根的右孩子.
类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);
}
代码源自此处.
这篇关于将排序后的数组插入二叉搜索树的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文