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

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

 

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 '
';
print_r($c);
?>

 

你可能感兴趣的:(leetcode)