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:
[4, 5, 3]
would result in this tree: 1
/
2
[2]
would result in this tree: 1
[1]
would result in the empty tree: []
Returns[4, 5, 3], [2], [1]
.
Credits:
Special thanks to@elmirapfor adding this problem and creating all test cases.
tag: binary tree
/**
* 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>> ans = new ArrayList<>();
if (root == null) return ans;
dfs(root, ans);
return ans;
}
private int dfs(TreeNode root, List<List<Integer>> ans){
if (root == null) return 0;
int height = 1 + Math.max(dfs(root.left, ans), dfs(root.right, ans));
if (ans.size() < height){
ans.add(new ArrayList<>());
}
ans.get(height - 1).add(root.val);
return height;
}
}