给出一个升序排序的数组,将其转化为平衡二叉搜索树(BST).
Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
思路:把中间位置的放在父节点上
<?php
class Node{
public $left = null;
public $right = null;
public $val;
public function __construct($val) {
$this->val = $val;
}
}
function sortedArrayToBST($arrNum, $head, $end) {
if ($head == $end) {
return null;
}
$mid = intval(($head + $end) / 2);
$node = new Node($arrNum[$mid]);
$node->left = sortedArrayToBST($arrNum, $head, $mid);
$node->right = sortedArrayToBST($arrNum, $mid + 1, $end);
return $node;
}
$arrNum = [1,2,3,4,5,6,7];
$node = sortedArrayToBST($arrNum, 0, count($arrNum));
output($node);
function output($node) {
print $node->val."\t";
print "左".$node->left->val."右".$node->right->val."\n";
if ($node->left != null) {
output($node->left);
}
if ($node->right != null) {
output($node->right);
}
print "\n";
}