根据有序数组构建二叉树

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

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

 

 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 }

 

转载于:https://www.cnblogs.com/aalex/p/5057440.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值