zoukankan      html  css  js  c++  java
  • leetcode -- 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,#,#,15,7},

        3
       / 
      9  20
        /  
       15   7
    

     return its zigzag level order traversal as:

    [
      [3],
      [20,9],
      [15,7]
    ]

    [解题思路]

    本题是二叉树层序遍历的变形,二叉树的层序遍历通过使用queue来实现,

    一开始我也试图用queue来解这题,第二层很好解决,但到第三层时无法实现从左到右遍历该层

    上网搜索了下,发现该题可以使用栈来解决,通过分析执行结果确实是后进先出

    这里通过定义leftToRight来表示是从左到右还是从右到左

    从左到右:先加left后加right

    从右到左:先加right后加left

     1 public ArrayList<ArrayList<Integer>> zigzagLevelOrder(TreeNode root) {
     2         // Start typing your Java solution below
     3         // DO NOT write main() function
     4         ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
     5         if(root == null){
     6             return result;            
     7         }
     8         Stack<TreeNode> curLvl = new Stack<TreeNode>();
     9         Stack<TreeNode> nextLvl = new Stack<TreeNode>();
    10         boolean leftToRight = true;
    11         curLvl.push(root);
    12         ArrayList<Integer> output = new ArrayList<Integer>();
    13         while(!curLvl.empty()){
    14             TreeNode curNode = curLvl.pop();
    15             output.add(curNode.val);
    16             if(leftToRight){
    17                 if(curNode.left != null){
    18                     nextLvl.add(curNode.left);
    19                 }
    20                 if(curNode.right != null){
    21                     nextLvl.add(curNode.right);
    22                 }
    23             } else{
    24                 if(curNode.right != null){
    25                     nextLvl.add(curNode.right);
    26                 }
    27                 if(curNode.left != null){
    28                     nextLvl.add(curNode.left);
    29                 }
    30             }
    31             if(curLvl.empty()){
    32                 result.add(output);
    33                 output = new ArrayList<Integer>();
    34                 leftToRight = !leftToRight;
    35                 curLvl.addAll(nextLvl);
    36                 nextLvl.clear();
    37             }
    38         }
    39         return result;
    40     }
  • 相关阅读:
    JAVA 8的新特性
    JAVA中map的分类和各自的特性
    设计模式之工厂方法模式(附实例代码下载)
    为什么重写equals还要重写hashcode??
    C# static的用法详解
    1-RadioButton控件的用法
    C#三种常用的读取XML文件的方法
    VS2017 中安装SVN
    pip安装selenium时,报错“You are using pip version 10.0.1, however version 18.0 is available.”的问题
    问题:unknown error: call function result missing 'value' 解决方法
  • 原文地址:https://www.cnblogs.com/feiling/p/3278691.html
Copyright © 2011-2022 走看看