难度系数 ⭐⭐
时间限制 C/C++ 1秒,其他语言2秒 空间限制:C/C++ 32M,其他语言64M
题目内容 从上往下打印出二叉树的每个节点,同层节点从左至右打印。
思路 设置一个队列,遍历树,初始将根节点加入到队列中。当队列非空时,将队头元素弹出,判断弹出元素是否有左、右孩子,若有,则将其加入队列(注意顺序)。循环至队列为空结束。
package nowcoder;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;
public class No24 {
public static class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
public static ArrayList<Integer> PrintFromTopToBottom(TreeNode root) {
ArrayList<Integer> res = new ArrayList<>();
if (root == null) return null;
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
while (!queue.isEmpty()){
TreeNode flag = queue.poll();
res.add(flag.val);
if (flag.left != null) queue.offer(flag.left);
if (flag.right != null) queue.offer(flag.right);
}
return res;
}
public static void printTree(TreeNode head) {
System.out.println("Binary Tree:");
printInOrder(head, 0, "H", 17);
System.out.println();
}
public static void printInOrder(TreeNode head, int height, String to, int len) {
if (head == null) {
return;
}
printInOrder(head.right, height + 1, "v", len);
String val = to + head.val + to;
int lenM = val.length();
int lenL = (len - lenM) / 2;
int lenR = len - lenM - lenL;
val = getSpace(lenL) + val + getSpace(lenR);
System.out.println(getSpace(height * len) + val);
printInOrder(head.left, height + 1, "^", len);
}
public static String getSpace(int num) {
String space = " ";
StringBuffer buf = new StringBuffer("");
for (int i = 0; i < num; i++) {
buf.append(space);
}
return buf.toString();
}
public static void main(String[] args){
TreeNode head = new TreeNode(1);
head.left = new TreeNode(2);
head.right = new TreeNode(3);
head.left.left = new TreeNode(4);
head.right.left = new TreeNode(5);
head.right.right = new TreeNode(6);
head.left.left.right = new TreeNode(7);
printTree(head);
System.out.println();
ArrayList<Integer> res = PrintFromTopToBottom(head);
for (int i = 0; i < res.size(); i++)
System.out.print(res.get(i) + " ");
}
}