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]
.
这道题一开始看到层遍历,想拿hashmap保存层跟list的关系,看了其他的网上的思路后突然明白不需要这么麻烦。因为在实现的时候是通过递归实现的,所以一定会从小的号开始递增,也就是说计算当前节点的结果之前,一定会计算它的孩子,而它的孩子的高度一定比他低,所以在结果里一定有比他深度低的元素,而且它不会比子节点超过1层。
所以这个算法的本质就是按层添加,属于哪一层的加到哪一层。
代码:
public List<List<Integer>> findLeaves(TreeNode root) {
//找到它的深度,然后把值存到hashmap对应key当中,就可以了
//HashMap<Integer, List<Integer>>
List<List<Integer>> result = new ArrayList<>();
int level = getLeaf(root, result);
return result;
}
private int getLeaf(TreeNode node, List<List<Integer>> result){
if(node == null) return -1;
int height = 1 + Math.max(getLeaf(node.left, result), getLeaf(node.right, result));
if(height>=result.size()){
result.add(new ArrayList<>());
}
result.get(height).add(node.val);
return height;
}