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

    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],
    ]
    解题思路: 使用BFS遍历树,将每一层放入一个ArrayList中。当一层结束后,将这个ArrayList插到最终的List的头部。
     1 /**
     2  * Definition for binary tree
     3  * public class TreeNode {
     4  *     int val;
     5  *     TreeNode left;
     6  *     TreeNode right;
     7  *     TreeNode(int x) { val = x; }
     8  * }
     9  */
    10 public class Solution {
    11 
    12     public ArrayList<ArrayList<Integer>> levelOrderBottom(TreeNode root) {
    13         // Start typing your Java solution below
    14         // DO NOT write main() function
    15         ArrayList<TreeNode> queue = new ArrayList<TreeNode>();
    16         ArrayList<ArrayList<Integer>> r = new ArrayList<ArrayList<Integer>>();
    17         if(root == null) return r;
    18         queue.add(root);
    19         TreeNode nl = new TreeNode(999);//999 是一个singal,表示一层结束了。
    20         queue.add(nl);
    21         ArrayList<Integer> cur = new ArrayList<Integer>();
    22         while(queue.size() != 1){
    23             TreeNode rn = queue.remove(0);
    24             if(rn.val == 999){
    25                 queue.add(nl);
    26                 r.add(0,cur);
    27                 cur = new ArrayList<Integer>();
    28             }
    29             else{
    30                 if(rn.left != null) queue.add(rn.left);
    31                 if(rn.right != null) queue.add(rn.right);
    32                 cur.add(rn.val);
    33             }
    34         }
    35         r.add(0,cur);
    36         return r;
    37     }
    38 }
  • 相关阅读:
    如何利用WGET覆写已存在的档案
    linux 脚本返回值
    ubuntu的配置网络
    非交互模式修改Ubuntu密码的命令
    [zz]python多进程编程
    [zz]linux修改密码出现Authentication token manipulation error的解决办法
    [zz]4.1.5 进程的处理器亲和性和vCPU的绑定
    vcpu
    非交互式调用交互式程序
    HDOJ_ACM_饭卡
  • 原文地址:https://www.cnblogs.com/reynold-lei/p/3320675.html
Copyright © 2011-2022 走看看