目录结构
1.题目
从上到下按层打印二叉树,同一层的节点按从左到右的顺序打印,每一层打印到一行。
示例:
给定二叉树: [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回其层次遍历结果:
[
[3],
[9,20],
[15,7]
]
提示:
节点总数 <= 1000
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/cong-shang-dao-xia-da-yin-er-cha-shu-ii-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
2.题解
通过变量记录获取每层的节点个数(或者通过队列大小获取每层节点个数)按层输出即可。
public class Offer32_2 {
@Test
public void test() {
TreeNode root = new TreeNode(1, new TreeNode(2, new TreeNode(4), null),
new TreeNode(3, null, new TreeNode(5)));
System.out.println(levelOrder1(root));
}
public List<List<Integer>> levelOrder(TreeNode root) {
if (root == null) {
return new ArrayList<>();
}
List<List<Integer>> resultList = new ArrayList<>();
Queue<TreeNode> queue = new ArrayDeque<>();
List<Integer> tmpList = new ArrayList<>();
queue.add(root);
int pre = 1, current = 0;
while (!queue.isEmpty()) {
TreeNode tmp = queue.poll();
tmpList.add(tmp.val);
if (tmp.left != null) {
current++;
queue.add(tmp.left);
}
if (tmp.right != null) {
current++;
queue.add(tmp.right);
}
if (--pre == 0) {
resultList.add(tmpList);
tmpList = new ArrayList<>();
pre = current;
current = 0;
}
}
return resultList;
}
public List<List<Integer>> levelOrder1(TreeNode root) {
if (root == null) {
return new ArrayList<>();
}
List<List<Integer>> resultList = new ArrayList<>();
Queue<TreeNode> queue = new ArrayDeque<>();
List<Integer> tmpList = new ArrayList<>();
queue.add(root);
while (!queue.isEmpty()) {
for (int i = queue.size(); i > 0; i--) {
TreeNode tmp = queue.poll();
tmpList.add(tmp.val);
if (tmp.left != null) {
queue.add(tmp.left);
}
if (tmp.right != null) {
queue.add(tmp.right);
}
}
resultList.add(tmpList);
tmpList = new ArrayList<>();
}
return resultList;
}
}
- 时间复杂度:
- 空间复杂度: