leetcode-108题-将有序数组转换为二叉搜索树

    技术2025-04-20  25

    https://leetcode-cn.com/problems/convert-sorted-array-to-binary-search-tree/

     

    <?php class TreeNode { public $val = null; public $left = null; public $right = null; function __construct($value) { $this->val = $value; } } class Solution { /** * @param Integer[] $nums * @return TreeNode */ function sortedArrayToBST($nums) { $size = count($nums); return $this->buildTree(0,$size-1,$nums); } function buildTree($left,$right,$arrays){ if($left > $right) return null; //防止溢出 $mid = ceil(($right-$left)/2) + $left; $node = new TreeNode($arrays[$mid]); $node->left = $this->buildTree($left,$mid-1,$arrays); $node->right = $this->buildTree($mid+1,$right,$arrays); return $node; } } $array = [1,2,3,4,5,6,7,8,9]; $s = new Solution(); $c = $s->sortedArrayToBST($array); echo '<pre>'; print_r($c); ?>

     

    Processed: 0.010, SQL: 9