zoukankan      html  css  js  c++  java
  • 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 class Solution {
     2     public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
     3         List<List<Integer>> res = new ArrayList<List<Integer>>();
     4         Queue<TreeNode> queue = new LinkedList<TreeNode>();
     5         if(root==null) return res;
     6         int flag =1;
     7         queue.add(root);
     8         while (!queue.isEmpty()) {
     9             int levlnum = queue.size();
    10             List<Integer> res_temp = new ArrayList<Integer>();
    11             for (int i = 0;i<levlnum ;i++ ){ //把每层的左右节点都保存到queue里 
    12                 //并讲当层的值从queue里弹出,加到res_temp 中
    13             if(queue.peek().left!=null) queue.add(queue.peek().left);
    14             if(queue.peek().right!=null) queue.add(queue.peek().right);
    15                 if(flag==1)
    16                 res_temp.add(queue.poll().val);
    17                 else
    18                 res_temp.add(0,queue.poll().val);
    19             }
    20             res.add(res_temp);
    21             flag = 1-flag;
    22         }
    23         return res;
    24     }
  • 相关阅读:
    python 数据类型 基础第二天
    Python基础第一篇
    前言、入门程序、常量、变量
    win10打开移动热点让手机连接上网教程
    win10移动热点问题
    博客园快速美化
    Idea提示没有符号类错误解决
    mybatis复习01
    test
    d190305面试题01总结
  • 原文地址:https://www.cnblogs.com/zle1992/p/8350511.html
Copyright © 2011-2022 走看看