zoukankan      html  css  js  c++  java
  • 根据有序数组构建二叉树

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

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

     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 }
  • 相关阅读:
    day 011总结
    day 010 总结
    day 10作业
    day 009总结
    day 008总结
    wireshark 解密tls消息
    js基础 数组slice
    js基础 数组splice
    js基础 Array.from
    js基础 Array.of
  • 原文地址:https://www.cnblogs.com/aalex/p/5057440.html
Copyright © 2011-2022 走看看