php二叉樹如何刪除節(jié)點(diǎn)

PHP
小樊
82
2024-10-17 19:37:06
欄目: 編程語言

在 PHP 中,要?jiǎng)h除二叉樹中的節(jié)點(diǎn),需要遵循以下步驟:

  1. 查找要?jiǎng)h除的節(jié)點(diǎn)
  2. 如果節(jié)點(diǎn)有兩個(gè)子節(jié)點(diǎn),找到其后繼節(jié)點(diǎn)(右子樹中的最小節(jié)點(diǎn)),用它來替換要?jiǎng)h除的節(jié)點(diǎn),然后刪除后繼節(jié)點(diǎn)。
  3. 如果節(jié)點(diǎn)只有一個(gè)子節(jié)點(diǎn)或沒有子節(jié)點(diǎn),用其子節(jié)點(diǎn)替換要?jiǎng)h除的節(jié)點(diǎn)。
  4. 如果找不到要?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

0