如何把一个有序的整数数组放到二叉树中
猿媛之家
已推送大量原创内容
已出版:
C、java、python、go、php、js、kotlin、scala、c#
等各种语言的面试笔试知识点书籍
已在菜单栏开源持续更新分类整理,干货满满
三步加星,方便阅读
本题来源:微软笔试题
难度指数:4 考察频率:3
分析与解答:
如果要把一个有序的整数数组放到二叉树中,那么所构造出来的二叉树必定也是一棵有序二叉树。鉴于此,实现思路为:取数组的中间元素作为根结点,将数组分成左右两部分,对数组的两部分用递归的方法分别构建左右子树,如下图所示。
如上图所示,首先取数组的中间结点6作为二叉树的根结点,把数组分成左右两部分,然后对于数组的左右两部分子数组分别运用同样的方法进行二叉树的构建。例如,对于左半部分子数组,取中间结点3作为树的根结点,再把孩子数组分成左右两部分。依此类推,就可以完成二叉树的构建,实现代码如下:
public class Test{/*方法功能:把有序数组转换为二叉树 */public static BiTNode arraytotree(int[] arr, int start, int end){BiTNode root=null;if(end>=start){root = new BiTNode();int mid=(start+end+1)/2;//树的根结点为数组中间的元素root.data = arr[mid];//递归的用左半部分数组构造root的左子树root.lchild=arraytotree(arr,start,mid-1);//递归的用右半部分数组构造root的右子树root.rchild=arraytotree(arr, mid+1, end);}else{root = null;}return root;}/* 用中序遍历的方式打印出二叉树结点的内容 */public static void printTreeMidOrder(BiTNode root) {if(root==null) return;//遍历root结点的左子树if(root.lchild!=null)printTreeMidOrder(root.lchild);//遍历root结点System.out.print(root.data+" ");//遍历root结点的右子树if(root.rchild!=null)printTreeMidOrder(root.rchild);}public static void main(String[] args){int arr[] = {1,2,3,4,5,6,7,8,9,10};System.out.print("数组:");for(int i=0;i<arr.length;i++)System.out.print(arr[i]+" ");System.out.println();BiTNode root;root=arraytotree(arr, 0,arr.length-1);System.out.print("转换成树的中序遍历为:");printTreeMidOrder(root);System.out.println();}}
程序的运行结果为
数组:1 2 3 4 5 6 7 8 9 10转换成树的中序遍历为:1 2 3 4 5 6 7 8 9 10
算法性能分析:
由于这种方法只遍历了一次数组,因此,算法的时间复杂度为O(N)。其中,N表示的是数组长度。
感谢您的阅读,有任何问题欢迎评论区留言。
