[leetcode]103. Binary Tree Zigzag Level Order Traversal二叉树来回遍历

Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from left to right, then right to left for the next level and alternate between).

For example:
Given binary tree [3,9,20,null,null,15,7],

    3
/ \
9 20
/ \
15 7

return its zigzag level order traversal as:

[
[3],
[20,9],
[15,7]
]

题目

[leetcode]103. Binary Tree Zigzag Level Order Traversal二叉树来回遍历

思路

1.  use Queue to help BFS

2. once scan current level, make a U-turn, then scan next level

代码

 class Solution {
public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
List<List<Integer>> result = new ArrayList<>();
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
int level = 0;
// lever order traversal
while (!queue.isEmpty()) {
int size = queue.size();
List<Integer> list = new ArrayList<>();
for (int i = 0; i < size; i++) {
TreeNode node = queue.remove();
if (node != null) {
list.add(node.val);8
queue.add(node.left);
queue.add(node.right);
}
}
if (!list.isEmpty()) {
// make a U-turn
if (level % 2 == 1) {
Collections.reverse(list);
}
result.add(list);
}
level++;
}
return result;
}
}
上一篇:Hadoop源码学习笔记之NameNode启动场景流程四:rpc server初始化及启动


下一篇:Angular2入门:TypeScript的函数 - 函数定义、可选参数、默认参数和函数重载