如何遍历一个亿节点的树php,二分搜索树 添加节点、遍历、最大深度的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);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值