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     }
  • 相关阅读:
    流行-Manifold学习理解与应用
    狠心奶奶自断亲情,28年后孙女拒绝相见:人有没有不原谅的权利?
    学术论文常用词汇总结(待更新)
    机动车驾驶(2)--- 老司机经验
    关于MySQL数据导出导入
    php5.6-lumen与php5.6-phalcon性能对比
    win7(64bit)+python3.5+pyinstaller3.2安装和测试
    WARNING: Can not get binary dependencies for file...
    一些不错的计算机书籍
    PHP扩展类ZipArchive实现压缩解压Zip文件和文件打包下载
  • 原文地址:https://www.cnblogs.com/feiling/p/3278691.html
Copyright © 2011-2022 走看看