简体   繁体   中英

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. 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). Howhever queue q just stays null. 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? The only way I see is to iterate over the elements from nextLevel and push them into q .

When you do

q = nextLevel;

you are just copying the reference, so when you clear nextLevel you lose all the elements.

Change

nextLevel.clear();

to

nextLevel = new LinkedList<Node>();

to point nextLevel to a new queue instead.

You only need one queue for a breadth first search (BFS) that at the end does what you need. When you put the children at the end of the queue, you still have the same level element in front of it. 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);
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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