22. Binary tree - find the width of the tree

Using a queue, a binary tree is traversed hierarchically. After the traversal of the previous layer is completed, all nodes of the next layer have been placed in the queue, and the number of elements in the queue at this time is the width of the next layer. By analogy, the maximum width of the binary tree can be obtained by traversing the next layer in turn.

 

package facehandjava.tree;

import java.util.LinkedList;
import java.util.Queue;

public class WidthTree {
   
public static Node init() { // Note that it must be built in reverse order, first create child nodes, and then build up in reverse order, because non- The leaf node will use the following nodes, and the initialization is initialized in order. If it is not built in reverse order, an error will be reported.
       
Node J = new Node( 8 , null , null );
        Node H =
new Node( 4 , null , null );
        Node G =
new Node( 2 , null , null );
        Node F =
new Node(7, null, J);
        Node E =
new Node(5, H, null);
        Node D =
new Node(1, null, G);
        Node C =
new Node(9, F, null);
        Node B =
new Node(3, D, E);
        Node A =
new Node(6, B, C);
       
return A;   //返回根节点
   
}

   
public static void main(String[] args) {
        Node root = WidthTree.init();
        System.
out.println("树的宽度");
       
int L = WidthTree(root);
        System.
out.println(L);
    }

   
public static int WidthTree(Node node) {
        Queue<Node> queue =
new LinkedList<>();
        queue.add(node);
       
int max = 0;
       
while (!queue.isEmpty()){
           
int size =queue.size();
            max = max > size ? max :size;
           
while (size> 0) {
                Node temp =queue.remove();
                size--;
                
if (temp.getLeftNode()!= null) {
                   queue.add(temp.getLeftNode());
                }
               
if (temp.getRightNode() != null) {
                   queue.add(temp.getRightNode());
                }
            }
        }
       
return max;
    }
}

 


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325541976&siteId=291194637