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; } }