【发布时间】:2016-07-26 02:55:30
【问题描述】:
我是树编码的新手。
给定以下输入数组 -
array(10,7,13,5,6,8,11,15,14,4,3,16)
我想通过一个一个地插入这些值来准备一棵平衡二叉树,从第一个元素开始(应该插入一个节点的左子节点,然后是右子节点,然后应该检查下一个节点以插入它的左边和正确的孩子。所有插入都应该先发生在一个级别,然后再插入到更高的级别)。结果应该是这样的 -
这是我现在拥有的代码(根据我找到的 BST 代码进行了一些修改 here)
<?php
class Node
{
public $left;
public $right;
public $data;
public function __construct($data)
{
$this->data = $data;
$this->right = NULL;
$this->left = NULL;
}
} //End class Node
class BTree
{
public $root;
public function __construct()
{
$this->root = NULL;
}
/* Insert the first node to the BST*/
public function insert($data)
{
$node = new Node($data);
if($this->root === NULL)
$this->root = $node;
else
$this->insertNode($this->root,$node);
}
/* Insert node starting from root */
public function insertNode(&$root,$node)
{
if($root === NULL)
{//root is not occupied, set root as the node
$root = $node;
}
else
{
if($root->left && $root->left->data===null)
{
$root->left==$node;
}
else
{
if($root->right && $root->right->data===null) //Not using else to avoid duplicate values
{
$root->right==$node;
}
else
{
$this->insertNode($root->left,$node); //Search for place in the right side to insert
}
}
}
}
/* Get an array and insert all items in it to the tree in the array order */
public function multiInsert($array)
{
foreach($array as $data)
$this->insert($data);
}
/*
Draw the tree from left to right
Line with same color are in same level of the tree
*/
public function draw($node = 'root', $depth = 0)
{
if($node == 'root') $node = $this->root; /* If node not selected the default is the tree root */
if ($node === null) return;
return
$this->draw($node->right, $depth + 1).str_repeat(" ", $depth).
"<span style='color:".(($depth%2 == 0)? 'red' : 'blue')."'>".$node->data."</span><br>".
$this->draw($node->left, $depth + 1);
}
} //End class BTree
/* ########### EXAMPLE ########### */
echo '<h1>Binary Tree</h1>';
$tree = new BTree();
$tree->multiInsert(array(10,7,13,5,6,8,11,15,14,4,3,16));
echo'<br><br>';
echo $tree->draw();
?>
这会导致一棵只有左孩子的树,如以下输出所示 -
【问题讨论】:
标签: php binary-tree