在 PHP 中,要刪除二叉樹中的節點,需要遵循以下步驟:
以下是一個簡單的 PHP 類,表示二叉樹及其節點,以及刪除節點的函數:
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;
}
}
使用這個類,你可以創建一個二叉樹并刪除指定值的節點:
$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);
這個例子將刪除值為 3 的節點,然后樹將變為:
5
/ \
2 7
/ \
6 8