1. 程式人生 > >LeetCode題庫解答與分析——#108. 將有序陣列轉換為二叉搜尋樹ConvertSortedArrayToSearchBinaryTree

LeetCode題庫解答與分析——#108. 將有序陣列轉換為二叉搜尋樹ConvertSortedArrayToSearchBinaryTree

將一個按照升序排列的有序陣列,轉換為一棵高度平衡二叉搜尋樹。

此題中,一個高度平衡二叉樹是指一個二叉樹每個節點的左右兩個子樹的高度差的絕對值不超過1。

示例:

給定有序陣列: [-10,-3,0,5,9],

一種可行答案是:[0,-3,9,-10,null,5],它可以表示成下面這個高度平衡二叉搜尋樹:

      0
     / \
   -3   9
   /   /
 -10  5

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

個人思路:

既然是有序陣列,則取中間項則可以保證最終得到的二叉搜尋樹為平衡的。於是取中間項為根節點,並將其左右分別拆分為左右子樹的陣列,用遞迴的方式再分別使其計算左右子樹的根節點,直到取得陣列為空返回空節點。

程式碼(JavaScript):

/**
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */
/**
 * @param {number[]} nums
 * @return {TreeNode}
 */
var sortedArrayToBST = function(nums) {
    if(nums.length==0){
        return null;
    }
    var l=nums.length;
    var half=parseInt(l/2);
    var root=new TreeNode(nums[half]);
    if(half==0){
        return root;
    }
    var left=new Array(half);
    var right=new Array(l-half-1);
    for(var i=0;i<left.length;i++){
        left[i]=nums[i];
    }
    root.left=arguments.callee(left);
    for(var i=0;i<right.length;i++){
        right[i]=nums[i+half+1];
    }
    root.right=arguments.callee(right);
    return root;
};