20200703:將有序數組轉換爲二叉搜索樹(leetcode108)

將有序數組轉換爲二叉搜索樹

題目

將有序數組轉換爲二叉搜索樹
在這裏插入圖片描述

思路與算法

  1. 乍一看很簡單,實際也很簡單,今天的動態規劃沒做出來,就刷每日一題好了。保證平衡的最簡單方法就是從每次都取最中間的數作爲當前樹或者子樹的root節點。代碼也沒啥太好解釋的,發現兩週前做過這題,再貼一下。

代碼實現

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public TreeNode sortedArrayToBST(int[] nums) {
        if(nums == null || nums.length == 0)
            return null;
        else
            return getTree(nums,0,nums.length-1);
    }
    public static TreeNode getTree(int[] nums,int left,int right){
        while(left<=right){
            int mid = (left+right)/2;
            TreeNode tn = new TreeNode(nums[mid]);
            tn.left = getTree(nums,left,mid-1);
            tn.right = getTree(nums,mid+1,right);
            return tn;
        }
        return null;
        
    }
}

複雜度分析

將數組遍歷了一遍,因此時間複雜度O(N)。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章