简体   繁体   中英

Print a Binary Tree (level by level) Java

I'm trying to make a class that prints my binary tree level by level .

I have here on my code classes that (1) inserts elements on my binary tree, (2) prints in an in-order, (3) prints in a post-order, (4) prints in a pre-order. And I need to create one more class that prints my binary trees in a tree-like structure (or pyramid like) I want to create a class that prints the elements of my binary tree like this:

在此处输入图像描述

Thank you!

public class MyBinaryTree { 
static class Node{
    char data;                      
    Node left;
    Node right;
    
    Node(char data){                
        left = right = null;        
        this.data = data;
    }
}

Node root;                  

MyBinaryTree(){
    root = null;                        
}                                       
public void insertElements() {
    Scanner scan = new Scanner(System.in);      
    String inputStr = new String();
    System.out.print("Input elements:");
    inputStr = scan.nextLine(); 

    for(int i = 0; i < inputStr.length(); i++) {    
        Insert(inputStr.charAt(i));                 
    }
}

public void Insert (char data) {                
    root = Insert(root, data);      
    numOfNodes++;                               
}                                                   
                                                    

Node Insert (Node node, char data) {
    if (node == null) {
        node = new Node(data);
    } else {
        if (data <= node.data) {                    
            node.left = Insert(node.left, data);    
        } else {
            node.right = Insert(node.right, data);  
        }                                           
    }
    return node;
    
}

}

Queue is best if you want to print level by level

    void printLevelOrder() {
    Queue<Node> queue = new LinkedList<Node>();
    queue.add(root);
    queue.add(null);
    while (!queue.isEmpty()) {

        Node temp = queue.poll();
        if(temp!=null)
            System.out.print(temp.data + " ");

        if(temp == null) {
            System.out.println();
            if(queue.isEmpty()) break;
            queue.add(null);
            continue;
        }

        /*Enqueue left child */
        if (temp.left != null) {
            queue.add(temp.left);
        }

        /*Enqueue right child */
        if (temp.right != null) {
            queue.add(temp.right);
        }
    }
}

Note: Adding null to queue is mentioning next line.

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