zoukankan      html  css  js  c++  java
  • [LintCode] Binary Tree Leaves Order Traversal

    Given a binary tree, collect a tree's nodes as if you were doing this: Collect and remove all leaves, repeat until the tree is empty.

    Example

    Given binary tree:

              1
             / 
            2   3
           /      
          4   5    
    

    Returns [[4, 5, 3], [2], [1]].

    If we assign a value of 1 to all leave nodes as their height,  then we can assign a value of 2 to the parent nodes of all leave nodes.

    Repeat this from bottom up until we've reached root node, which has the biggest height value. Since we need to start the assign

    from bottom, we need to use depth first search. For leave nodes, they should be added from left to right, so for a given node, 

    its left child is visited first, then its right child.

    To get the height of a given node, we need to get both children node's height first, then pick the bigger one plus 1. This is an indication 

    of post order traversal.

    Algorithm: 

    1. do a post order traversal on given binary tree, assigning a height value to each node.

         height = max {left child's height, right child's height} + 1;

        add each node's value to a list and establish a mapping between height and a list.

        Nodes with the same height are put in the same list. Post order ensures that all leave nodes are added

      from left side to right side.

    2. Iterate all map keys in increasing order and get each list.

     1 public class Solution {
     2     private HashMap<Integer, List<Integer>> height = new HashMap<>();
     3     public List<List<Integer>> findLeaves(TreeNode root) {
     4         List<List<Integer>> result = new ArrayList<>();
     5         int max_Height = getNodeHeight(root);
     6         for(int i = 1; i <= max_Height; i++) {
     7             result.add(height.get(i));
     8         }
     9         return result;
    10     }
    11     
    12     private int getNodeHeight(TreeNode node) {
    13         if(node == null) {
    14             return 0;
    15         }
    16         int leftH = getNodeHeight(node.left);
    17         int rightH = getNodeHeight(node.right);
    18         int h = Math.max(leftH, rightH) + 1;
    19         if(!height.containsKey(h)) {
    20             height.put(h, new ArrayList<Integer>());
    21         }
    22         height.get(h).add(node.val);
    23         return h;
    24     }
    25 }

    Related Problems 

    Minimum Depth of Binary Tree

    Maximum Depth of Binary Tree

  • 相关阅读:
    3. Image Structure and Generation
    STM32F103
    10.2 External interrupt/event controller (EXTI)
    10.1 Nested vectored interrupt controller (NVIC) 嵌套矢量中断控制器
    ibatis 使用 in 查询的几种XML写法
    文字纵向打印
    oracle每天清理归档日志
    使用语句查询mssql死锁
    Xml序列化UTF-8格式错误
    Nginx的优点
  • 原文地址:https://www.cnblogs.com/lz87/p/7478942.html
Copyright © 2011-2022 走看看