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

    Question

    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]
    ]

    Solution

    Same method as "Binary Tree Level Order Traversal". Note that for ArrayList, it has function add(int index, E element).

     1 /**
     2  * Definition for a binary tree node.
     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         List<List<Integer>> result = new ArrayList<List<Integer>>();
    13         if (root == null)
    14             return result;
    15         Deque<TreeNode> prev = new ArrayDeque<TreeNode>();
    16         Deque<TreeNode> current;
    17         TreeNode tmpNode;
    18         prev.addLast(root);
    19         while (prev.size() > 0) {
    20             current = new ArrayDeque<TreeNode>();
    21             List<Integer> tmpList = new ArrayList<Integer>();
    22             while (prev.size() > 0) {
    23                 tmpNode = prev.pop();
    24                 if (tmpNode.left != null)
    25                     current.addLast(tmpNode.left);
    26                 if (tmpNode.right != null)
    27                     current.addLast(tmpNode.right);
    28                 tmpList.add(tmpNode.val);
    29             }
    30             prev = current;
    31             result.add(0, tmpList);
    32         }
    33         return result;        
    34     }
    35 }
  • 相关阅读:
    Windows7共享设置
    13-运算符
    13-数据类型转换
    06-移动web之flex布局
    09-sass
    08-less预处理器
    移动端必须掌握知识点
    11-JS变量
    10-响应式
    07-rem
  • 原文地址:https://www.cnblogs.com/ireneyanglan/p/4834086.html
Copyright © 2011-2022 走看看