zoukankan      html  css  js  c++  java
  • 把排序数组转换为高度最小的二叉搜索树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 }
  • 相关阅读:
    史上最强验证
    Yii2 return redirect()
    一次线上问题引发的思考
    一次前端体验优化
    RSA For PHP
    判断是否字符串是否是JSON
    过滤Xss
    Yii2 中日志的记录
    Yii2 中禁用csrf校验
    开始。
  • 原文地址:https://www.cnblogs.com/wangnanabuaa/p/5014886.html
Copyright © 2011-2022 走看看