剑指 Offer 32 - II. 从上到下打印二叉树 II
难度简单
从上到下按层打印二叉树,同一层的节点按从左到右的顺序打印,每一层打印到一行。
例如:
给定二叉树: [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回其层次遍历结果:
[
[3],
[9,20],
[15,7]
]
提示:
-
节点总数 <= 1000
注意:本题与主站 102 题相同:https://leetcode-cn.com/problems/binary-tree-level-order-traversal/
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
if(root==null) {
return new ArrayList<>();
}
List<List<Integer>> result = new ArrayList<>();
LinkedList<TreeNode> linkedList = new LinkedList<>();
linkedList.add(root);
while (!linkedList.isEmpty()) {
List<Integer> list = new ArrayList<>();
for (int i = linkedList.size(); i > 0; i--) {
TreeNode temp = linkedList.pop();
list.add(temp.val);
if (temp.left != null) {
linkedList.add(temp.left);
}
if (temp.right != null) {
linkedList.add(temp.right);
}
}
result.add(list);
}
return result;
}
}