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     }
  • 相关阅读:
    脚手架自建从开始到发布
    零散点总结
    2019.3.7 chrome72下载图片卡死问题
    2019.2.18 一九年的新篇章
    2018.10.12 布局终结
    2018.7.23 放大缩小菜单
    2018.7.19 横向收缩菜单动画
    2018.6.8 openlayers.js学习(汇总)
    Elasticsearch 排序
    easyui tree树节点上移下移 选中节点加背景色
  • 原文地址:https://www.cnblogs.com/zle1992/p/8350511.html
Copyright © 2011-2022 走看看