zoukankan      html  css  js  c++  java
  • Binary Tree Level Order Traversal II leetcode java

    题目

    Given a binary tree, return the bottom-up level order traversal of its nodes' values. (ie, from left to right, level by level from leaf to root).

    For example:
    Given binary tree {3,9,20,#,#,15,7},

        3
       / 
      9  20
        /  
       15   7
    

    return its bottom-up level order traversal as:

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

    题解
    这道题跟前面一道是一样的。。
    只是存到res的结果顺序不一样罢了。
    之前那个就是循序的存
    这道题就是每得到一个行结果就存在res的0位置,这样自然就倒序了。

    代码如下:
     1     public ArrayList<ArrayList<Integer>> levelOrderBottom(TreeNode root) {
     2         ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();  
     3         if(root == null)  
     4             return res;
     5         
     6         LinkedList<TreeNode> queue = new LinkedList<TreeNode>();  
     7         queue.add(root);
     8         
     9         int curLevCnt = 1;  
    10         int nextLevCnt = 0;  
    11         
    12         ArrayList<Integer> levelres = new ArrayList<Integer>();  
    13        
    14         while(!queue.isEmpty()){  
    15             TreeNode cur = queue.poll();  
    16             curLevCnt--;  
    17             levelres.add(cur.val);  
    18             
    19             if(cur.left != null){  
    20                 queue.add(cur.left);  
    21                 nextLevCnt++;  
    22             }  
    23             if(cur.right != null){  
    24                 queue.add(cur.right);  
    25                 nextLevCnt++;  
    26             }  
    27               
    28             if(curLevCnt == 0){  
    29                 curLevCnt = nextLevCnt;  
    30                 nextLevCnt = 0;  
    31                 res.add(0,levelres);  //insert one by one from the beginning
    32                 levelres = new ArrayList<Integer>();  
    33             }  
    34         }  
    35         return res;  
    36     }


  • 相关阅读:
    如何在IIS添加MIME扩展类型
    如何在ASP.NET的web.config配置文件中添加MIME类型
    Entity Framework 数据库先行、模型先行、代码先行
    Entity Framework 代码先行之约定配置
    netcore3.0 IOptions 选项(一)
    netcore3.0 IFileProvider 文件系统
    netcore3.0 IServiceCollection 依赖注入系统(三)
    netcore3.0 IServiceCollection 依赖注入系统(二)
    netcore3.0 IServiceCollection 依赖注入系统(一)
    netcore3.0 IConfiguration配置源码解析(四)
  • 原文地址:https://www.cnblogs.com/springfor/p/3891392.html
Copyright © 2011-2022 走看看