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

  • 相关阅读:
    网络编程
    面向对象总结
    面象对象编程(选课系统)
    类的魔法方法和部分单例模式
    简易3D开发,ThingJS之大道至简
    ThingJS参与3D众创,一起建设“实体中国”!
    ThingJS:轻松让空间“立起来”,展示你的3D创造力
    一个产品的状态不好?ThingJS来找茬
    ThingJS提供有地理位置的信息弹窗示例
    一次灵感盛宴,ThingJS推出场景Market
  • 原文地址:https://www.cnblogs.com/lz87/p/7478942.html
Copyright © 2011-2022 走看看