zoukankan      html  css  js  c++  java
  • Convert Sorted Array to Binary Search Tree

    题目:

    Given an array where elements are sorted in ascending order, convert it to BST

    解答:

     1 public class Solution {
     2 
     3     public static void main(String[] args) {
     4         int[] num = {1,2,3,4,5};
     5 
     6         TreeNode root = sortedArrayToBST(num);
     7 
     8         InOrder(root);
     9 
    10     }
    11 
    12     public static TreeNode sortedArrayToBST(int[] num) {
    13         return sortedArrayToBST(num, 0, num.length-1);
    14     }
    15 
    16     private static sortedArrayToBST(int[] arr, int start, int end) {
    17         if(start > end) {
    18             return null;
    19         }
    20 
    21         int mid = (start + end) >> 1;
    22         TreeNode node = new TreeNode(arr[mid]);
    23         node.left = sortedArrayToBST(arr, start, mid-1);
    24         node.right = sortedArrayToBST(arr, mid+1, end);
    25         return node;
    26     }
    27 
    28     public static void InOrder(TreeNode root) {
    29 
    30         if(root == null) {
    31             return;
    32         }
    33 
    34         if(root.left != null) {
    35             InOrder(root.left);
    36         }
    37 
    38         System.out.println(root.val);
    39 
    40         if(root.right != null) {
    41             InOrder(root.right);
    42         }
    43 
    44     }
    45 }

  • 相关阅读:
    linux压缩与解压
    simple 单例
    模板字符串
    变量的解构赋值
    let和const关键字
    React的基本认识
    Docker安装Nginx
    jenkins创建工程
    Jenkins系统初始化配置
    在CentOS上使用Docker镜像安装Jenkins
  • 原文地址:https://www.cnblogs.com/wylwyl/p/10419085.html
Copyright © 2011-2022 走看看