zoukankan      html  css  js  c++  java
  • LeetCode 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]
    ]



     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     public List<List<Integer>> levelOrderBottom(TreeNode root) {
    12             LinkedList<List<Integer>> resList= new LinkedList<>();
    13             
    14             if (root==null) {
    15                 return resList;
    16             }
    17             
    18             Deque<TreeNode> visitDeque=new LinkedList<>();
    19             List<Integer>    currList;
    20             visitDeque.add(root);
    21             int count=1;
    22             int level=0;
    23             while (!visitDeque.isEmpty()) {
    24                 level=0;
    25                 currList=new ArrayList<Integer>();
    26                 for (int i = 0; i < count; i++) {
    27                     TreeNode     node=visitDeque.pop();
    28                     currList.add(node.val);
    29                     if (node.left != null) {
    30                         ++level;
    31                         visitDeque.add(node.left);
    32                     }
    33                     if (node.right != null) {
    34                         ++level;
    35                         visitDeque.add(node.right);
    36                     }
    37                 }
    38                 count=level;
    39                 resList.addFirst(currList);
    40             }
    41             return resList;
    42     }
    43 }
  • 相关阅读:
    蘑菇街电话面试记录
    阿里校招在线笔试
    前端小记
    校招记录
    leetcode部分解题思路
    搜的面试题零散记录
    网页小记录
    开机进入GRUB不要慌,命令行也可启动Linux
    Error running Tomcat 6: Address localhost:8080 is already in use
    IDEA 自动提示快捷键,类似VS Ctrl + J
  • 原文地址:https://www.cnblogs.com/birdhack/p/4039048.html
Copyright © 2011-2022 走看看