February 5, 2024

Viiisit [LeetCode] - 108. Convert Sorted Array to Binary Search Tree

#php#javascript#ruby

keep learning, keep coding!

Problem - Convert Sorted Array to Binary Search Tree

Given an integer array nums where the elements are sorted in ascending order, convert it to a
height-balanced binary search tree.

翻譯蒟蒻

將一個已經按升序排列的整數陣列轉換成一個高度平衡的二元搜尋樹(BST)。



先找出樹的根節點,由於陣列已經按升序排列,可以選擇陣列的中間元素作為樹的根節點,這樣可以確保左右子樹的大小相對平衡,接著分別遞迴處理左右子樹。


Solution - JavaScript

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {number[]} nums
* @return {TreeNode}
*/
var sortedArrayToBST = function(nums) {
if (nums.length === 0) return null;

// 找到陣列的中間索引
let mid = Math.floor(nums.length / 2);
let root = new TreeNode(nums[mid]);
root.left = sortedArrayToBST(nums.slice(0, mid));
root.right = sortedArrayToBST(nums.slice(mid + 1));
return root;
};

Solution - Ruby

1
2
3
4
5
6
7
8
9
def sorted_array_to_bst(nums)
return nil if nums.empty?
return TreeNode.new(nums[0]) if nums.size == 1
mid = nums.size / 2
root = TreeNode.new(nums[mid])
root.left = sorted_array_to_bst(nums[0...mid])
root.right = sorted_array_to_bst(nums[mid+1..-1])
return root
end

Solution - PHP

1
2
3
4
5
6
7
8
9
10
function sortedArrayToBST($nums) {
if (count($nums) === 0) {
return null;
}
$mid = floor(count($nums) / 2);
$node = new TreeNode($nums[$mid]);
$node->left = $this->sortedArrayToBST(array_slice($nums, 0, $mid));
$node->right = $this->sortedArrayToBST(array_slice($nums, $mid + 1));
return $node;
}

LeetCode 傳送門 - Convert Sorted Array to Binary Search Tree