zoukankan      html  css  js  c++  java
  • leetcode366- 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:
    Given binary tree 

              1
             / 
            2   3
           /      
          4   5    

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

    Explanation:

    1. Removing the leaves [4, 5, 3] would result in this tree:

              1
             / 
            2          

    2. Now removing the leaf [2] would result in this tree:

              1          

    3. Now removing the leaf [1] would result in the empty tree:

              []         
    

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

    算法:DFS递归,边计算节点深度边做。helper里做的是把深度相同的节点放到一个map的记录里。之后主函数就可以直接对深度相同的一类节点的值放到一个list。

    数据结构:Map<Integer, Set<TreeNode>>。记录某个深度(integer)对应的所有树节点(Set<TreeNode>)

    细节:1.map.containsKey()不要只写contains();map.keySet(),k不要大写。  2.List<Integer>里是.add(node.val)不是add(node)  3.每次private函数名字、参数改了一定要到所有调用这个函数的地方都改一遍!尤其是递归的时候千万小心!

    实现:

    /**
     * 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<>();
            Map<Integer, Set<TreeNode>> map = new HashMap<>();
            helper(root, map);
            for (int i = 1; i <= map.keySet().size(); i++) {
                List<Integer> l = new ArrayList<>();
                for (TreeNode n : map.get(i)) {
                    l.add(n.val);
                }
                result.add(l);
            }           
            return result;
        }
        
        private int helper(TreeNode root, Map<Integer, Set<TreeNode>> map) {
            
            if (root == null) {
                return 0;
            }
            
            int left = helper(root.left, map);
            int right = helper(root.right, map);
            int depth = Math.max(left, right) + 1;
            
            if (!map.containsKey(depth)) {
                map.put(depth, new HashSet<TreeNode>());
            }
            map.get(depth).add(root);
            
            return depth;
        }
    }
  • 相关阅读:
    表格标签
    常用标签
    标签笔记
    基础标签与格式
    态度!
    如何修改数据 练习
    增删查练习
    登陆注册练习
    PHP 数据访问
    PHP 基础知识测试题 答案分析
  • 原文地址:https://www.cnblogs.com/jasminemzy/p/7918396.html
Copyright © 2011-2022 走看看