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

  • 相关阅读:
    01背包--小P寻宝记——粗心的基友
    StringIndexOutOfBoundsException
    2014秋C++ 第8周项目 分支程序设计
    【JavaScript】正則表達式
    专业函数画图软件Origin
    设计模式学习–Decorator
    python使用requests模块模拟登陆知乎
    分享几个比较好的站点
    【转载】selenium之 定位以及切换frame(iframe)
    判断Selenium加载完成
  • 原文地址:https://www.cnblogs.com/lz87/p/7478942.html
Copyright © 2011-2022 走看看