我对我的二进制搜索树进行了4种不同的遍历。我被困在最后一个级别上,它是级别顺序遍历,似乎无法找到正确执行方法的方法。
主要问题是我不知道一次只能搜索一个级别,只能弄清楚如何搜索整个左子树或整个右子树。
private void preOrder(BinaryNode<AnyType> t )
{
if(isEmpty()){
System.out.println("Empty");
}
if(t != null) {
System.out.println(t.element);
preOrder(t.left);
preOrder(t.right);
}
}
private void postOrder(BinaryNode<AnyType> t){
if(isEmpty()){
System.out.println("Empty");
}
if (t != null) {
postOrder(t.left);
postOrder(t.right);
System.out.println(t.element);
}
}
private void inOrder(BinaryNode<AnyType> t)
{
if(isEmpty()){
System.out.println("Empty");
}
if (t != null) {
inOrder(t.left);
System.out.println(t.element);
inOrder(t.right);
}
}
private void levelOrder(BinaryNode<AnyType> t, int level)
{
if(isEmpty()){
System.out.println("Empty");
}
if(height(t) == 2) {
System.out.println(t.element);
}else if(height(t) > 1){
levelOrder(t.left, level );
levelOrder(t.right, level );
}
}
答案 0 :(得分:0)
您的方法看起来像DFS方法。它可能不遵循该方法。 尝试在此处使用Queue,它将帮助您正确遍历。 因为它将遵循BFS方法,所以您可以逐级遍历。 添加第一个左节点,然后添加右节点,并按照以下步骤进行。
答案 1 :(得分:0)
以“回合”序列查看整个搜索,每个级别一个“回合”。
每一轮:
- initialize a "next round" list of nodes to empty
- process a prepared list of nodes (the ones that are at that level and thus to be searched in that round) whereby for each node :
- do the actual comparison
- add all the node's child nodes to the "next round" list
从仅填充根节点的“下一轮”列表开始该过程。
重复直到“下一轮”节点列表为空或您找到了要查找的内容。
答案 2 :(得分:0)
这就是我的方法。
private void levelOrder(BinaryNode root) {
if (root == null) {
return;
}
Queue<BinaryNode> q = new LinkedList<>();
// Pushing root node into the queue.
q.add(root);
// Executing loop till queue becomes
// empty
while (!q.isEmpty()) {
BinaryNode curr = q.poll();
System.out.print(curr.element + " ");
// Pushing left child current node
if (curr.left != null) {
q.add(curr.left);
}
// Pushing right child current node
if (curr.right != null) {
q.add(curr.right);
}
}
}