[LeetCode 366] Find Leaves of Binary Tree (Medium)

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:

Input: [1,2,3,4,5]
  
          1
         / \
        2   3
       / \     
      4   5    

Output: [[4,5,3],[2],[1]]

Solution: Bottom - up

  1. 根据题目分析,可以发现,所有叶子节点[4,5,3],其height为1; [2]height为2; [1]height为3.
  2. 所以可以采用bottom-up的方式,找到所有节点的height,把height相同的节点归成一类,就是答案。
  3. 归类可以用HashMap数据结构: key: height, value: List of Node
// hashmap to store, height and all nodes with this height
Map<Integer, List<Integer>> tracker = new HashMap<> ();

Code

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public List<List<Integer>> findLeaves(TreeNode root) {
        List<List<Integer>> result = new ArrayList<> ();
        if (root == null) {
            return result;
        }
        
        // hashmap to store, height and all nodes with this height
        Map<Integer, List<Integer>> tracker = new HashMap<> ();
        
        // recurse to popular the hashmap
        getHeights (root, tracker);
        
        for (Map.Entry <Integer, List<Integer>> entrySet : tracker.entrySet ()) {
            result.add (entrySet.getValue ());
        }
        
        return result;
    }
    
    private int getHeights (TreeNode root, Map<Integer, List<Integer>> tracker) {
        if (root == null) {
            return 0;
        }
        
        int leftHeight = getHeights (root.left, tracker);
        int rightHeight = getHeights (root.right, tracker);
        
        int currentHeight = Math.max (leftHeight, rightHeight) + 1;
        
        List<Integer> nodes = tracker.getOrDefault (currentHeight, new ArrayList<Integer> ());
        nodes.add (root.val);
        tracker.put (currentHeight, nodes);

        return currentHeight;
    }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容