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     }
  • 相关阅读:
    selenium的持续问题解决
    为什么使用Nginx
    [转]性能测试场景设计深度解析
    [转]CentOS7修改时区的正确姿势
    [转]利用Fiddler模拟恶劣网络环境
    [转]什么是微服务
    [转] WebSocket 教程
    [转] Python实现简单的Web服务器
    shell修改配置文件参数
    [转] linux shell 字符串操作(长度,查找,替换)详解
  • 原文地址:https://www.cnblogs.com/feiling/p/3278691.html
Copyright © 2011-2022 走看看