好吧,为了简单起见,我使用一个名为的类构建了一个基本的二叉搜索树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));
现在的问题是,如果我想打印树的漂亮文本图,我该如何遍历树。我对如何在树的特定级别上正确遍历感到困惑。构建树时我错过了一个重要的变量吗?