Prove safety offer: up to the next print binary tree (java)

Title: Printing from the top of each node binary tree, the same one node print order from left to right.

For example input binary tree:

      8
    /  \
   6    10
  /\     /\
 5  7   9  11

The first print out 8,6,10,5,7,9

  Printing process is as follows: prints the root, in order to print the next two child nodes of the node 8, we should traverse the node when the stored value of 6 and two nodes 10 to the one container now there are two nodes within the container. Printed from left to right as required, we remove the first node value of 6. 6 prints out its value after 5 and 7, respectively, of two data nodes into the container. In this case there are three data nodes container, 10,5,7 respectively. Next, we removed the node 10 from the data value for the container. Noting the node 10 is the value of the ratio of 5,7, a first node into a container, this time off than to remove these two nodes, this is what we typically say FIFO, it is not difficult to see that the container it should be a queue. Since the value of the node have no child nodes 5,7,9,11, so long as printing can be sequentially.

 public <E> void   printFromTopToBottom(BinaryTreeNode root){  
        if(root == null)  
            return;  
        Queue<BinaryTreeNode> queue = new LinkedList<BinaryTreeNode>();  
        queue.add(root);  
        while(!queue.isEmpty()){  
            BinaryTreeNode node = queue.poll();  
            System.out.print(node.value+",");  
            if(node.leftNode != null)  
                queue.add(node.leftNode);  
            if(node.rightNode != null)  
                queue.add(node.rightNode);  
        }  
    }  



Published 118 original articles · won praise 35 · views 120 000 +

Guess you like

Origin blog.csdn.net/abc7845129630/article/details/52729131