在 PHP 中,要?jiǎng)h除二叉樹中的節(jié)點(diǎn),需要遵循以下步驟:
以下是一個(gè)簡(jiǎn)單的 PHP 類,表示二叉樹及其節(jié)點(diǎn),以及刪除節(jié)點(diǎn)的函數(shù):
class TreeNode {
public $value;
public $left;
public $right;
public function __construct($value) {
$this->value = $value;
$this->left = null;
$this->right = null;
}
}
class BinaryTree {
public $root;
public function __construct() {
$this->root = null;
}
public function deleteNode($value) {
$this->root = $this->deleteNodeRecursive($this->root, $value);
}
private function deleteNodeRecursive($node, $value) {
if ($node === null) {
return null;
}
if ($value < $node->value) {
$node->left = $this->deleteNodeRecursive($node->left, $value);
} elseif ($value > $node->value) {
$node->right = $this->deleteNodeRecursive($node->right, $value);
} else {
if ($node->left === null) {
return $node->right;
} elseif ($node->right === null) {
return $node->left;
}
$node->value = $this->findMin($node->right)->value;
$node->right = $this->deleteNodeRecursive($node->right, $node->value);
}
return $node;
}
private function findMin($node) {
while ($node->left !== null) {
$node = $node->left;
}
return $node;
}
}
使用這個(gè)類,你可以創(chuàng)建一個(gè)二叉樹并刪除指定值的節(jié)點(diǎn):
$tree = new BinaryTree();
$tree->root = new TreeNode(5);
$tree->root->left = new TreeNode(3);
$tree->root->right = new TreeNode(7);
$tree->root->left->left = new TreeNode(2);
$tree->root->left->right = new TreeNode(4);
$tree->root->right->left = new TreeNode(6);
$tree->root->right->right = new TreeNode(8);
$tree->deleteNode(3);
這個(gè)例子將刪除值為 3 的節(jié)點(diǎn),然后樹將變?yōu)椋?/p>
5
/ \
2 7
/ \
6 8