题目1
从上往下打印出二叉树的每个节点,同层节点从左至右打印。
思路
- 借助队列
- 打印根节点(1)时,左右子节点(2,3)入队;然后队头是下一个根节点(2),打印后出队,其左右子(4,5)再入队;(现在队头是3,打印3,左右子入队。。。)
代码
import java.util.ArrayList;
import java.util.Queue;
import java.util.LinkedList;
/**
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
public class Solution {
public ArrayList<Integer> PrintFromTopToBottom(TreeNode root) {
//借助队列
Queue<TreeNode> queue = new LinkedList<TreeNode>();
queue.add(root);
ArrayList<Integer> arr = new ArrayList<>();
if(root == null) return arr;
while(root != null){
//打印当前节点的值,同时保存当前节点的左右子
arr.add(root.val);
queue.poll();
if(root.left != null){
queue.add(root.left);
}
if(root.right != null){
queue.add(root.right);
}
root = queue.peek();
}
return arr;
}
}
题目2
分行从上到下打印二叉树
思路
- 设置两个变量,一个表示当前层中还没有打印的节点数,另一个表示下一层中要打印的节点数
代码
public class Solution {
public ArrayList<Integer> PrintFromTopToBottom(TreeNode root) {
//借助队列
Queue<TreeNode> queue = new LinkedList<TreeNode>();
queue.add(root);
int nextLevel = 0;
int toBePrinted = 1;
ArrayList<Integer> arr = new ArrayList<>();
if(root == null) return arr;
while(root != null){
//打印当前节点的值,同时保存当前节点的左右子
arr.add(root.val);
queue.poll();
if(root.left != null){
queue.add(root.left);
++nextLevel;
}
if(root.right != null){
queue.add(root.right);
++nextLevel;
}
root = queue.peek();
--toBePrinted;
if(toBePrinted == 0){
printf("\n");
toBePrinted = nextLevel;
nextLevel = 0;
}
}
return arr;
}
}