Я пытаюсь распечатать все узлы в двоичном дереве поиска из указанного c узла. Вот код, который я использовал до сих пор:
public void printLevel(Key key)
{
//If we have no tree then return
if (root == null)
{
return;
}
//Create a new queue to store the printed nodes
Queue<Node> queue = new LinkedList<Node>();
//Enqueue the root in case we need it
queue.add(root);
//Traverse the tree to find the right node
while (queue.size() > 0)
{
//Compare the key to see where we need to go next
int cmp = key.compareTo(root.key);
if (cmp == 0) //Match
{
//Print out the nodes from the match
int nodeCount = queue.size();
while (nodeCount > 0)
{
//Print out the contents of the node and
Node n = queue.peek();
System.out.println(n.val);
queue.remove();
//If the left and right nodes are not null, add them
//to the queue
if (n.left != null)
{
queue.add(n.left);
}
if (n.right != null)
{
queue.add(n.right);
}
nodeCount--;
}
} else if (cmp < 0) //Go Left
{
//Move the root to the left and add that node to the queue
root = root.left;
queue.add(root);
} else if (cmp > 0)
{
//Move the root to the right and add that node to the queue
root = root.right;
queue.add(root);
}
}
}
Каждый раз, когда я запускаю это, я получаю некоторые действительно странные результаты. как показано ниже:
Перед балансом: ДЕСЯТЬ ТРИ ОДИН ПЯТЬ ДВА СЕМЬ
После баланса: ТРИ СЕМЬ ПЯТЬ ОДИН СЕМЬ ПЯТЬ ДВАДЦАТЬ ПЯТЬ ДЕСЯТЬ
После того, как баланс должен выглядеть следующим образом : ПЯТЬ ДВА ДЕСЯТЬ РАЗ ТРИ СЕМЬ
Я делаю что-то не так в своем алгоритме печати или мне нужно go пересмотреть мой алгоритм баланса и помощников?