根据有序数组构建二叉树

根据一个有序数组,构造一颗二叉搜索树

思路:因为数组有序,所以数组中间节点是该二叉树的根节点,因为二叉树的定义是右子树都大于根节点,左子树都小于根节点,构造完根节点后,分别截取数组的前半段和后半段分别递归构造左子树和右子树

 

 1 package com.rui.microsoft;
 2 
 3 public class Test86_BuildBSTByArray {
 4 
 5     public static void main(String[] args) {
 6         int[] a = {1,2,3,4,5};
 7         Test86_BuildBSTByArray app = new Test86_BuildBSTByArray();
 8         Node root = app.build(a, 0, a.length-1);
 9         System.out.println(root.value);
10     }
11     
12     Node build(int[] a, int start, int end){
13         if(start > end) return null;
14         int mid = start + (end - start) / 2;
15         Node root = new Node(a[mid]);
16         root.left = build(a, start, mid - 1);
17         root.right = build(a, mid+1,end);
18         return root;
19     }
20     
21     static class Node{
22         int value;
23         Node left;
24         Node right;
25         Node(int v){
26             this.value = v;
27         }
28     }
29 }

 

posted @ 2015-12-18 16:28  蟹粉小笼包  阅读(718)  评论(0编辑  收藏  举报