二分搜索树 添加节点、遍历、最大深度的php版本
2020-01-10 本文已影响0人
博楠同学
<?php
/**
* 节点值重复的会跳过,类似集合
*/
/**
* 节点类
*/
class Node
{
public $value;
public $left = null;
public $right = null;
public function __construct($value)
{
# code...
$this->value = $value;
}
}
/**
* 操作类
*/
class tree
{
public $root = null;//根节点
public $size = null; //节点个数
public $values = []; //保存遍历树结构的值
public $depth = 0; //树高度
public function add($value)
{
if ($this->root == null) {
$this->root = new Node($value);
$this->size ++;
} else {
// var_dump($this->root);
$this->root = $this->insert($this->root, new Node($value));
}
return $this->root;
}
//向已root为根节点的二分搜索树种插入元素node
public function insert($root, $node)
{
// var_dump($root);
//终止条件
if ($root == null) {
return $node;
}
if ($node->value > $root->value) {
$root->right = $this->insert($root->right, $node);
$this->size ++;
} else if ($node->value < $root->value){
$root->left = $this->insert($root->left, $node);
$this->size ++;
}
return $root;
}
public function select($node)
{
//终止条件
if ($node == null) {
return null;
}
$this->values[] = $node->value;//前序遍历
$this->select($node->left);
// $this->values[] = $node->value;//中序遍历
$this->select($node->right);
// $this->values[] = $node->value;//后续遍历
}
public function height($node, $depth)
{
if ($node == null) {
return null;
}
$this->height($node->left, $depth + 1);
$this->height($node->right, $depth + 1);
$this->depth = $this->depth < $depth + 1 ? $depth + 1 : $this->depth;
}
}
//制作一些数据
$tree = new tree();
foreach ([28, 16, 13, 22, 30, 29, 42, 45] as $value) {
//添加一个值到二分搜索树中
$tree->add($value);
}
//打印二分搜索树结构
// var_dump($tree->root);
//遍历二分搜索树结构
// $tree->select($tree->root);
// var_dump($tree->values);
//二分搜索树的高度
$tree->height($tree->root, 0);
var_dump($tree->depth);