制作二叉搜索树 [英] making binary search tree
本文介绍了制作二叉搜索树的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我有一个包含100个元素的数组列表,如 {3,2,6,7,...,99}
,我如何制作BST?
How do I make a BST when I have an array list of 100 elements like {3,2,6,7,...,99}
?
推荐答案
我相信 TreeSet
是二叉搜索树的实现。由于整数具有自然排序,您可以简单地遍历整数数组并将它们全部添加到 TreeSet< Integer>
。
I believe TreeSet
is an implementation of a binary search tree. Since integers have a natural ordering you could simply loop through your array of integers and add them all to a TreeSet<Integer>
.
另请注意,有一种方法 Arrays.binarySearch
在排序数组中执行二进制搜索。
Note also, that there is a method Arrays.binarySearch
that does a binary search in a sorted array.
int[] someInts = {3,2,6,7, /*...,*/ 99};
// use a TreeSet
TreeSet<Integer> ints = new TreeSet<Integer>();
for (int i : someInts)
ints.add(i);
System.out.println(ints.contains(2)); // true
System.out.println(ints.contains(5)); // false
// or sort the array and use Arrays.binarySearch
Arrays.sort(someInts);
System.out.println(Arrays.binarySearch(someInts, 2) >= 0); // true
System.out.println(Arrays.binarySearch(someInts, 5) >= 0); // false
这篇关于制作二叉搜索树的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文