-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFind_Leaves_of_Binary_Tree.java
More file actions
44 lines (35 loc) · 1.12 KB
/
Copy pathFind_Leaves_of_Binary_Tree.java
File metadata and controls
44 lines (35 loc) · 1.12 KB
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
366. Find Leaves of Binary Tree
Given a binary tree, find all leaves and then remove those leaves. Then repeat the previous steps until the tree is empty.
Example:
Given binary tree
1
/ \
2 3
/ \
4 5
Returns [4, 5, 3], [2], [1].
Explanation:
1. Remove the leaves [4, 5, 3] from the tree
1
/
2
2. Remove the leaf [2] from the tree
1
3. Remove the leaf [1] from the tree
[]
Returns [4, 5, 3], [2], [1].
//https://discuss.leetcode.com/topic/49194/10-lines-simple-java-solution-using-recursion-with-explanation
public class Solution {
public List<List<Integer>> findLeaves(TreeNode root) {
List<List<Integer>> res = new ArrayList<>();
height(root, res);
return res;
}
private int height(TreeNode node, List<List<Integer>> res){
if(null==node) return -1;
int level = 1 + Math.max(height(node.left, res), height(node.right, res));
if(res.size()<level+1) res.add(new ArrayList<>());
res.get(level).add(node.val);
return level;
}
}