第 32-2 题:分行从上往下打印二叉树
传送门:分行从上往下打印二叉树,牛客网 online judge 地址。
从上到下按层打印二叉树,同一层的结点按从左到右的顺序打印,每一层打印到一行。
样例:
输入如下图所示二叉树
[8, 12, 2, null, null, 6, null, 4, null, null, null]
8 / \ 12 2 / 6 / 4
输出:
[[8], [12, 2], [6], [4]]
分析:与“不分行从上往下打印二叉树”的区别就在于,在从队列中取出元素的之前,先看看队列中有多少元素,然后依次将这些元素全部取出来。取出来以后,再将左右子树的根结点加入队列。
Python 代码:
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def printFromTopToBottom(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
if root is None:
return []
queue = [root]
res = []
while queue:
size = len(queue)
cur_list = []
for _ in range(size):
top = queue.pop(0)
cur_list.append(top.val)
if top.left:
queue.append(top.left)
if top.right:
queue.append(top.right)
res.append(cur_list)
return res
Java 代码:
import java.util.ArrayList;
import java.util.LinkedList;
class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
// 从上到下按层打印二叉树,同一层结点从左至右输出。每一层输出一行。
// 层序遍历
public class Solution {
ArrayList<ArrayList<Integer>> Print(TreeNode pRoot) {
ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();
if (pRoot == null) {
return res;
}
LinkedList<TreeNode> queue = new LinkedList<>();
queue.addLast(pRoot);
while (!queue.isEmpty()) {
int size = queue.size();
ArrayList<Integer> curLevel = new ArrayList<>();
for (int i = 0; i < size; i++) {
TreeNode top = queue.removeFirst();
curLevel.add(top.val);
if (top.left != null) {
queue.addLast(top.left);
}
if (top.right != null) {
queue.addLast(top.right);
}
}
res.add(curLevel);
}
return res;
}
}