forked from fishercoder1534/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFindLeavesofBinaryTree.java
52 lines (40 loc) · 1.11 KB
/
FindLeavesofBinaryTree.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
package com.fishercoder.solutions;
import com.fishercoder.common.classes.TreeNode;
import java.util.ArrayList;
import java.util.List;
/**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].
*/
public class FindLeavesofBinaryTree {
List<List<Integer>> result = new ArrayList<List<Integer>>();
public List<List<Integer>> findLeaves(TreeNode root) {
dfs(root);
return result;
}
int dfs(TreeNode root){
if(root == null) return 0;
int level = Math.max(dfs(root.left), dfs(root.right))+1;
if(result.size() < level){
result.add(new ArrayList<Integer>());
}
result.get(level-1).add(root.val);
return level;
}
}