这是我参与8月更文挑战的第15天,活动详情查看:8月更文挑战
剑指 Offer 32 - II. 从上到下打印二叉树 II
题目
从上到下按层打印二叉树,同一层的节点按从左到右的顺序打印,每一层打印到一行。
例如: 给定二叉树: [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回其层次遍历结果:
[
[3],
[9,20],
[15,7]
]
提示:
节点总数 <= 1000
方法一
层次遍历:每次记录入队的元素个数cnt,每次出队只出前一次入队的个数,即cnt
/**
* 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) {
List<List<Integer>> res = new ArrayList<>();
LinkedList<TreeNode> queue = new LinkedList<>();
if (root == null) return res;
int cnt = 1;
queue.addLast(root);
while(queue.size() > 0) {
int k = 0;
ArrayList<Integer> path = new ArrayList<>();
while((cnt --) > 0) {
TreeNode cur = queue.getFirst();
path.add(cur.val);
queue.removeFirst();
if (cur.left != null) {
queue.addLast(cur.left);
k ++;
}
if (cur.right != null) {
queue.addLast(cur.right);
k ++;
}
}
res.add(path);
cnt = k;
}
return res;
}
}
时间复杂度: O(n)
空间复杂度: O(n)
剑指 Offer 32 - III. 从上到下打印二叉树 III
题目
请实现一个函数按照之字形顺序打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右到左的顺序打印,第三行再按照从左到右的顺序打印,其他行以此类推。
例如: 给定二叉树: [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回其层次遍历结果:
[
[3],
[20,9],
[15,7]
]
方法一
在剑指 Offer 32 - III. 从上到下打印二叉树 II的基础上,判断一下当前该层是否需要反向加元素即可。
/**
* 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) {
List<List<Integer>> res = new ArrayList<>();
LinkedList<TreeNode> queue = new LinkedList<>();
if (root == null) return res;
int cnt = 1, flag = 0;
queue.addLast(root);
while(queue.size() > 0) {
int k = 0;
LinkedList<Integer> path = new LinkedList<>();
while((cnt --) > 0) {
TreeNode cur = queue.getFirst();
if ((flag & 1) == 0)
path.addLast(cur.val);
else
path.addFirst(cur.val);
queue.removeFirst();
if (cur.left != null) {
queue.addLast(cur.left);
k ++;
}
if (cur.right != null) {
queue.addLast(cur.right);
k ++;
}
}
res.add(path);
cnt = k;
flag ++;
}
return res;
}
}
时间复杂度: O(n)
空间复杂度: O(n)