简体   繁体   English

逐级打印二叉树的节点(Java)

[英]Print Nodes of a Binary Tree level by level (Java)

I want to print nodes of a binary tree level by level. 我想逐级打印二叉树的节点。 For this I read this post: http://leetcode.com/2010/09/printing-binary-tree-in-level-order.html and I want to implement the method using two queues. 为此,我阅读了这篇文章: http : //leetcode.com/2010/09/printing-binary-tree-in-level-order.html ,我想使用两个队列来实现该方法。 This is my method: 这是我的方法:

 private static void printByLevel2(Node root) {
    q = new LinkedList<Node>();
    q.add(root);
    Queue<Node> nextLevel = new LinkedList<Node>();
    while(!q.isEmpty()){
        Node n = q.remove();
        printNode(n);
        if(hasLeftChild(n)){
            nextLevel.add(n.left);
        }
        if(hasRightChild(n)){
            nextLevel.add(n.right);
        }
        if(q.isEmpty()){
            System.out.println();
            q = nextLevel;
            nextLevel.clear();
        }
    }
}

Howhever it doesnt work. 但是,它不起作用。 On the line q = nextLevel I want the queue q to points to the queue nextLevel (ie the one thet contains the nodes of the next level). 在行q = nextLevel我希望队列q指向队列nextLevel (即一个包含下一个级别的节点)。 Howhever queue q just stays null. 但是,队列q保持为空。 Can someone explain me why? 有人可以解释我为什么吗? Also if I want to 'transfer' the nodes from queue nextLevel to queue q how should I do it fast? 另外,如果我想将节点从“队列下nextLevel ”转移到队列“ q ”,我应该如何快速呢? The only way I see is to iterate over the elements from nextLevel and push them into q . 我看到的唯一方法是遍历nextLevel的元素并将其推入q

When you do 当你做

q = nextLevel;

you are just copying the reference, so when you clear nextLevel you lose all the elements. 您只是在复制参考,所以当您清除nextLevel您将丢失所有元素。

Change 更改

nextLevel.clear();

to

nextLevel = new LinkedList<Node>();

to point nextLevel to a new queue instead. nextLevel指向新队列。

You only need one queue for a breadth first search (BFS) that at the end does what you need. 广度优先搜索(BFS)只需要一个队列,该队列最后可以满足您的需求。 When you put the children at the end of the queue, you still have the same level element in front of it. 当您将子级放在队列的末尾时,您仍然在其前面具有相同的level元素。 So you can do it this way instead 所以你可以这样做

Queue<Node> q = new LinkedList<Node>();
while(!q.isEmpty()){
    Node n = q.remove();
    printNode(n);
    if(hasLeftChild(n)){
        q.add(n.left);
    }
    if(hasRightChild(n)){
        q.add(n.right);
    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM