zoukankan      html  css  js  c++  java
  • [leetcode]103. Binary Tree Zigzag Level Order Traversal二叉树Z形遍历

    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 }
  • 相关阅读:
    Asp.net 中 listbox 滚动条 定位 火麒
    Silverlight跨域访问WCF服务 火麒
    网页加载速度优化技巧
    很漂亮的login
    ireport
    方法1,定位,相当于四周受力
    方法2,平移
    大端小端数据存储方式
    c++中RTTI
    C语言细节数组a+1和&a+1
  • 原文地址:https://www.cnblogs.com/liuliu5151/p/9824000.html
Copyright © 2011-2022 走看看