108. Convert Sorted Array to Binary Search Tree

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

For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.

Example:

Given the sorted array: [-10,-3,0,5,9],
One possible answer is: [0,-3,9,-10,null,5], which represents the following height balanced BST:
? ? 0
? ? /\
? -3 9
? / ? /
-10 5

題目

把一個有序數(shù)組轉(zhuǎn)換成二叉樹,要求左右深度不能大于一。

思路

有這個深度要求,我們就只能從中間一分為二,對于左右子樹,也同樣一分為二,所以就是遞歸去做。

代碼

 public TreeNode sortedArrayToBST(int[] nums) {
         if (nums==null) {
            return null;
        }
         
        return convertTree(nums,0,nums.length-1);//遞歸函數(shù)
        }


    private TreeNode convertTree(int[] nums, int l, int r) {
        if (l<=r) {
            int mid =(l+r)/2;
            TreeNode root=new TreeNode(nums[mid]);//取中間的值為根節(jié)點
            root.left=convertTree(nums, l, mid-1);//遞歸獲得左右子樹
            root.right=convertTree(nums, mid+1, r);
            return root;
        }else {
            return null;
        }
    }
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容