返回
构建平衡二叉树,Leetcode 108 题深入浅出解析
见解分享
2023-10-10 01:19:00
题目概述
Leetcode 第 108 题“将有序数组转换为二叉搜索树”要求我们把一个顺序数组转换为一棵平衡二叉搜索树。平衡二叉搜索树是一类具有出色查找性能的数据结构,其中任何节点的左右子树的高度差至多为 1。
解题思路
一种巧妙的解决方法是利用数组有序的特点。我们从数组的中间元素开始,将其作为二叉搜索树的根节点。然后,我们将数组分为左右两部分,左边元素构成左子树,右边元素构成右子树。对左右子树继续递归地应用同样的方法,直到数组为空。
算法实现
/**
* Definition for a binary tree node.
*/
class TreeNode {
public $val = null;
public $left = null;
public $right = null;
function __construct($value) {
$this->val = $value;
}
}
/**
* LeetCode 108: Convert Sorted Array to Binary Search Tree
*
* @param Integer[] $nums
* @return TreeNode
*/
function sortedArrayToBST($nums) {
if (empty($nums)) {
return null;
}
$mid = floor(count($nums) / 2);
$root = new TreeNode($nums[$mid]);
$root->left = sortedArrayToBST(array_slice($nums, 0, $mid));
$root->right = sortedArrayToBST(array_slice($nums, $mid + 1));
return $root;
}
代码实例
$nums = [-10, -3, 0, 5, 9];
$root = sortedArrayToBST($nums);
echo "Inorder traversal of the constructed BST: ";
inorder($root);
function inorder($node) {
if ($node) {
inorder($node->left);
echo $node->val . " ";
inorder($node->right);
}
}
复杂度分析
该算法的时间复杂度为 O(n log n),其中 n 是数组的长度。这是因为我们每次将数组分为两半,然后递归地应用同样的方法。递归的深度为 log n,而每次递归需要对数组进行一次划分,时间复杂度为 O(n),因此总的时间复杂度为 O(n log n)。
该算法的空间复杂度为 O(log n),这是因为递归需要使用栈空间,而栈的深度为 log n。
总结
在本文中,我们讨论了 Leetcode 第 108 题“将有序数组转换为二叉搜索树”的解决方法。我们介绍了一种巧妙的递归算法,该算法的时间复杂度为 O(n log n),空间复杂度为 O(log n)。通过代码实例和复杂度分析,我们对该算法有了更深入的理解。