标签:null https code count secondary class 资料 badge imp
103. 二叉树的锯齿形层次遍历
103. Binary Tree Zigzag Level Order Traversal
题目描述
给定一个二叉树,返回其节点值的锯齿形层次遍历。(即先从左往右,再从右往左进行下一层遍历,以此类推,层与层之间交替进行)。
LeetCode103. Binary Tree Zigzag Level Order Traversal中等
例如:
给定二叉树 [3,9,20,null,null,15,7],
3
/ 9 20
/ 15 7
返回锯齿形层次遍历如下:
[
[3],
[20,9],
[15,7]
]
Java 实现
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
class Solution {
public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
if (root == null) {
return new LinkedList<>();
}
List<List<Integer>> res = new LinkedList<>();
int count = 1;
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
while (!queue.isEmpty()) {
int size = queue.size();
List<Integer> list = new LinkedList<>();
for (int i = 0; i < size; i++) {
TreeNode node = queue.poll();
list.add(node.val);
if (node.left != null) {
queue.offer(node.left);
}
if (node.right != null) {
queue.offer(node.right);
}
}
if (count % 2 == 0) {
Collections.reverse(list);
}
count++;
res.add(list);
}
return res;
}
}
相似题目
参考资料
LeetCode 103. 二叉树的锯齿形层次遍历(Binary Tree Zigzag Level Order Traversal)
标签:null https code count secondary class 资料 badge imp
原文地址:https://www.cnblogs.com/hglibin/p/10961254.html