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 }
  • 相关阅读:
    http协议详谈
    配置nginx 反向代理
    利用background-positon,background-image ,实现背景渐变
    vue +webpack 打包配置优化
    记项目中易出现的bug点
    vue 中基于html5 drag drap的拖放
    vue 项目技巧
    完整项目搭建全过程(vue-cli+webpack)
    vue+ D3+drag
    项目总结(3.28)
  • 原文地址:https://www.cnblogs.com/ireneyanglan/p/4834086.html
Copyright © 2011-2022 走看看