• convert sorted array/list to a height balanced BST.


    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) {
    // Start typing your Java solution below
    // DO NOT write main() function
    if(num==null)
    return null;
    
    int start = 0;
    int end = num.length-1;
    
    return sortedArrayToBST(num,start,end);
    }
    
    public TreeNode sortedArrayToBST(int[] num,int start,int end)
    {
    if(num==null)
    return null;
    
    while(start<=end)
    {
    int mid = start + (end-start)/2;
    TreeNode n = new TreeNode(num[mid]);
    n.left = sortedArrayToBST(num,start,mid-1);
    n.right = sortedArrayToBST(num,mid+1,end);
    return n;
    }
    return null;
    }
    }




    
    
     
  • 相关阅读:
    一个页面从输入 URL 到页面加载显示完成,这个过程中都发生了什么?
    210902
    1-2
    1-1
    4
    3
    2
    1
    u编码
    windows java 安装版 控制面板
  • 原文地址:https://www.cnblogs.com/anorthwolf/p/3091187.html
Copyright © 2020-2023  润新知