[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]
]

题目

思路

1.  use Queue to help BFS

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

代码

 1 class Solution {
 2     public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
 3         List<List<Integer>> result = new ArrayList<>();
 4         Queue<TreeNode> queue = new LinkedList<>();
 5         queue.add(root);
 6         int level = 0;
 7         // lever order traversal
 8         while (!queue.isEmpty()) {
 9             int size = queue.size();
10             List<Integer> list = new ArrayList<>();
11             for (int i = 0; i < size; i++) {
12                 TreeNode node = queue.remove();
13                 if (node != null) {
14                     list.add(node.val);8
15                     queue.add(node.left);
16                     queue.add(node.right);
17                 }
18             }
19             if (!list.isEmpty()) {
20                 // make a U-turn
21                 if (level % 2 == 1) {
22                     Collections.reverse(list);
23                 }
24                 result.add(list);
25             }
26             level++;
27         }
28         return result;
29     }
30 }

猜你喜欢

转载自www.cnblogs.com/liuliu5151/p/9824000.html