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
- 根据题目分析,可以发现,所有叶子节点如
[4,5,3]
,其height为1;[2]
height为2;[1]
height为3. - 所以可以采用
bottom-up
的方式,找到所有节点的height,把height相同的节点归成一类,就是答案。 - 归类可以用
HashMap
数据结构:key: height
,value: List of Node
// hashmap to store, height and all nodes with this height
Map> 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> findLeaves(TreeNode root) {
List> result = new ArrayList<> ();
if (root == null) {
return result;
}
// hashmap to store, height and all nodes with this height
Map> tracker = new HashMap<> ();
// recurse to popular the hashmap
getHeights (root, tracker);
for (Map.Entry > entrySet : tracker.entrySet ()) {
result.add (entrySet.getValue ());
}
return result;
}
private int getHeights (TreeNode root, Map> 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 nodes = tracker.getOrDefault (currentHeight, new ArrayList ());
nodes.add (root.val);
tracker.put (currentHeight, nodes);
return currentHeight;
}
}