public ArrayList<Integer> PrintFromTopToBottom(TreeNode root) {
ArrayList<Integer> res=new ArrayList<>();
if (root==null){
return res;
}
ArrayList<TreeNode> queue=new ArrayList<>();
queue.add(root);
while (queue.size()!=0){
TreeNode currNode= queue.remove(0);
res.add(currNode.val);
if (currNode.left!=null){
queue.add(currNode.left);
}
if (currNode.right!=null){
queue.add(currNode.right);
}
}
return res;
}
import java.util.LinkedList;
import java.util.Queue;
public class LevelPrint {
public static class Node {
public int value;
public Node left;
public Node right;
public Node(int data) {
this.value = data;
}
}
public static void levelPrint(Node head){
System.out.println("按层打印结果: ↓");
if (head==null){
return;
}
Queue<Node> queue=new LinkedList<>();
queue.offer(head);
while (!queue.isEmpty()){
head=queue.poll();
System.out.print(head.value+" ");
if (head.left!=null){
queue.offer(head.left);
}
if (head.right!=null){
queue.offer(head.right);
}
}
}
public static void main(String[] args){
Node head = new Node(5);
head.left = new Node(3);
head.right = new Node(8);
head.left.left = new Node(2);
head.left.right = new Node(4);
head.left.left.left = new Node(1);
head.right.left = new Node(7);
head.right.left.left = new Node(6);
head.right.left.left.left = new Node(1151);
head.right.right = new Node(10);
head.right.right.left = new Node(9);
head.right.right.right = new Node(11);
levelPrint(head);
}
}