[英]Print a Binary Tree (level by level) Java
I'm trying to make a class that prints my binary tree level by level .我正在尝试制作一个class 逐级打印我的二叉树。
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.我的代码类中有(1)在我的二叉树上插入元素,(2)按顺序打印,(3)按后序打印,(4)按预序打印。 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:
我需要再创建一个 class 以树状结构(或金字塔状)打印我的二叉树 我想创建一个 class 来打印我的二叉树的元素,如下所示:
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.注意:将 null 添加到队列中是指下一行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.