写一个二叉树php代码,function
时间: 2023-08-12 14:05:32 浏览: 69
实用的php二叉树代码
下面是一个简单的二叉树 PHP 代码,包括二叉树的节点结构和基本操作函数:
```php
class Node {
public $value;
public $left;
public $right;
function __construct($val) {
$this->value = $val;
$this->left = null;
$this->right = null;
}
}
class BinaryTree {
public $root;
function __construct() {
$this->root = null;
}
function insert($val) {
$newNode = new Node($val);
if ($this->root === null) {
$this->root = $newNode;
} else {
$current = $this->root;
while (true) {
if ($val < $current->value) {
if ($current->left === null) {
$current->left = $newNode;
break;
} else {
$current = $current->left;
}
} else {
if ($current->right === null) {
$current->right = $newNode;
break;
} else {
$current = $current->right;
}
}
}
}
}
function search($val) {
$current = $this->root;
while ($current !== null) {
if ($val === $current->value) {
return true;
} elseif ($val < $current->value) {
$current = $current->left;
} else {
$current = $current->right;
}
}
return false;
}
function inorderTraversal($node, &$result) {
if ($node === null) {
return;
}
$this->inorderTraversal($node->left, $result);
$result[] = $node->value;
$this->inorderTraversal($node->right, $result);
}
function preorderTraversal($node, &$result) {
if ($node === null) {
return;
}
$result[] = $node->value;
$this->preorderTraversal($node->left, $result);
$this->preorderTraversal($node->right, $result);
}
function postorderTraversal($node, &$result) {
if ($node === null) {
return;
}
$this->postorderTraversal($node->left, $result);
$this->postorderTraversal($node->right, $result);
$result[] = $node->value;
}
}
```
这个代码包含了二叉树的基本操作,包括插入节点、查找节点、中序、前序、后序遍历等。
阅读全文