Given an array where elements are sorted in ascending order, convert it to a height balanced BST.(示例

Posted Adding

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Given an array where elements are sorted in ascending order, convert it to a height balanced BST.(示例相关的知识,希望对你有一定的参考价值。

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
      public TreeNode sortedArrayToBST(int[] num) {
                if(num==null||num.length==0){
            return null;
        }
        int length=num.length;
        TreeNode treenode=sortedArrayToBST(num,0,length-1);//我每次总是忘记减一,以后要记住
        return treenode ;
        
    }

    private TreeNode sortedArrayToBST(int[] num, int star, int tail) {
          if(star>tail){
            return null;
        }
        int mid=star+(tail-star+1)/2;
        TreeNode root=new TreeNode(num[mid]);
        root.left=sortedArrayToBST(num,star,mid-1);
        root.right=sortedArrayToBST(num,mid+1,tail);
        return root;
    }
}

 

以上是关于Given an array where elements are sorted in ascending order, convert it to a height balanced BST.(示例的主要内容,如果未能解决你的问题,请参考以下文章

[?]*Shuffle an array

215. Kth Largest Element in an Array

[GeeksForGeeks] Cyclically rotate an array by one

215. Kth Largest Element in an Array

215. Kth Largest Element in an Array

215. Kth Largest Element in an Array