さて、簡単にするために呼び出されたクラスを使用して、基本的な二分探索ツリーを構築します。ノードNode
に使用されるコア メソッドを含めます。insert
public function addNode($node)
{
if ($this->left == null && $node->getValue() < $this->value) {
$this->left = $node;
$this->left->parent = $this;
return;
}
if ($this->right == null && $node->getValue() > $this->value) {
$this->right = $node;
$this->right->parent = $this;
return;
}
if ($node->getValue() < $this->getValue()) {
$this->left->addNode($node);
return;
}
if ($node->getValue() > $this->getValue()) {
$this->right->addNode($node);
return;
}
}
Node クラスにこれらの基本メンバー変数があります
private $left = null;
private $right = null;
private $value = null;
private $parent = null;
ノードを追加するだけでツリーを構築できます。
$node = new Node(5);
$node->addNode(new Node(7));
$node->addNode(new Node(3));
$node->addNode(new Node(4));
問題は、ツリーの素敵なテキスト図を印刷したい場合、どのようにツリーをトラバースするかです。ツリーの特定のレベルを右にトラバースする方法がわかりません。ツリーを構築するときに重要な変数を見逃していませんか?