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

  • 相关阅读:
    JavaScript中需要注意的几个问题
    前端编码规范之JavaScript
    那些年,我们一起玩过的响应式布局
    前端编码规范之CSS
    一个不陌生的JS效果-marquee,用css3来实现
    解读jQuery中extend函数
    字体大小自适应纯css解决方案
    浅谈叶小钗面试的几个问题
    【Python开发】C和Python之间的接口实现
    【Python开发】【编程开发】各种系统的清屏操作命令
  • 原文地址:https://www.cnblogs.com/lz87/p/7478942.html
Copyright © 2011-2022 走看看