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

    题目含义:给定一棵二叉树,从上到下,进行Z字行分层遍历的,即:本层的话从左打到右,那么下层就是从右到左,最后输出结果。

     1     public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
     2        List<List<Integer>> result = new ArrayList<>();
     3         if (root == null) return result;
     4         Queue<TreeNode> q = new LinkedList<>();
     5         q.add(root);
     6         
     7         boolean shunshizhen = false;
     8         while (!q.isEmpty())
     9         {
    10             int size = q.size();
    11             List<Integer> values = new ArrayList<>();
    12             for (int i=0;i<size;i++)
    13             {
    14                 TreeNode node  = q.poll();
    15                 values.add(node.val);
    16                 if (shunshizhen)
    17                 {
    18                     if (node.left !=null) q.offer(node.left);
    19                     if (node.right !=null) q.offer(node.right);      
    20                 }else
    21                 {
    22                     if (node.right !=null) q.offer(node.right);
    23                     if (node.left !=null) q.offer(node.left);
    24                 }
    25             }
    26             shunshizhen = shunshizhen?false:true;
    27             result.add(values);
    28         }
    29         return result;        
    30     }
  • 相关阅读:
    操作系统概述总结
    string类的用法总结
    stack的简单用法总结
    递归用法总结
    C语言中常见的图形打印总结
    C++中list的用法总结
    STL中find和sort的用法总结
    unity Physics/Physics2DProjectSettings中LayerCollisionMatrix的存储方式
    UnityEvent<T> 系列化
    十字相乘法
  • 原文地址:https://www.cnblogs.com/wzj4858/p/7715422.html
Copyright © 2020-2023  润新知