Well i build a basic Binary Search Tree using a class called Node
for simplicity i will include the core method that is used to insert
Nodes
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;
}
}
i have these basic member vars in the Node class
private $left = null;
private $right = null;
private $value = null;
private $parent = null;
I can construct a tree by simply adding nodes to it.
$node = new Node(5);
$node->addNode(new Node(7));
$node->addNode(new Node(3));
$node->addNode(new Node(4));
Now the question is how do i traverse the tree if i want to print a nice text diagram of the tree. I am confused on how to traverse right on a specific level of the tree. did i miss an important variable when constructing the tree?
A breadth first traversal is what you looking for:
Well Samuel already told you about breadth first traversal as I was writing this little function but still... I think that's what you're looking for.
The answer would depend on what order you want to traverse the tree, but a general depth-first traversal would look like:
From the comment you want breadth-first traversal. See this question about breadth-first traversal in Java. You can apply the same algorithm. How do implement a breadth first traversal?