二叉树的锯齿形层次遍历-二叉树
程序员文章站
2022-11-14 18:30:22
leetcode-103 二叉树的锯齿形层次遍历这题与102题无异,只需对于保存结果的偶数行进行一次反转。可用(Collections.reverse())/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */...
这题与102题无异,只需对于保存结果的偶数行进行一次反转。可用(Collections.reverse())
/**
* 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>> zigzagLevelOrder(TreeNode root) {
List<List<Integer>> res = new ArrayList<>();
if (root == null) return res;
Queue<TreeNode> q = new LinkedList<>();
q.offer(root);
while(! q.isEmpty()){
int size = q.size();
List<Integer> list = new ArrayList<>();
for (int i = 0; i < size; i++){
TreeNode node = q.poll();
list.add(node.val);
if (node.left != null){
q.offer(node.left);
}
if (node.right != null){
q.offer(node.right);
}
}
res.add(list);
}
// 翻转偶数行
for (int i = 0; i < res.size(); i++){
if (i % 2 == 1){
Collections.reverse(res.get(i));
}
}
return res;
}
}
本文地址:https://blog.csdn.net/liu_tian_wei/article/details/109636675