• 把排序数组转换为高度最小的二叉搜索树convert-sorted-array-to-binary-search-tree-with-minimal-height


    给一个排序数组(从小到大),将其转换为一棵高度最小的排序二叉树。

    样例

    给出数组 [1,2,3,4,5,6,7], 返回

         4
       /   
      2     6
     /     / 
    1   3  5   7
     1 /**
     2  * Definition of TreeNode:
     3  * public class TreeNode {
     4  *     public int val;
     5  *     public TreeNode left, right;
     6  *     public TreeNode(int val) {
     7  *         this.val = val;
     8  *         this.left = this.right = null;
     9  *     }
    10  * }
    11  */ 
    12 public class Solution {
    13     /**
    14      * @param A: an integer array
    15      * @return: a tree node
    16      */
    17     public TreeNode sortedArrayToBST(int[] A) {  
    18         // write your code here
    19         if(A.length ==0 )  return null;
    20         return sortedToBST(A, 0, A.length-1);
    21     }
    22     public TreeNode sortedToBST(int[] A,int start,int end){
    23         if (start > end)
    24             return null;
    25         int mid = (start+end)/2;
    26         TreeNode root = new TreeNode(A[mid]);
    27         root.left = sortedToBST(A,start,mid-1);
    28         root.right  = sortedToBST(A,mid+1,end);
    29         return root;
    30     }
    31 }
  • 相关阅读:
    C# Func的同步、异步调用
    C#以管理员身份运行程序
    C# 代码编程规范
    C# DES加密解密
    C# MD5加密
    EntityFramework查询--联合查询(Join,GroupJoin)
    C# 图片和Base64之间的转换
    php 验证身份证号
    Vue环境搭建
    PHP 3种方法实现采集网站数据
  • 原文地址:https://www.cnblogs.com/wangnanabuaa/p/5014886.html
Copyright © 2020-2023  润新知