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].
Solution1:遞歸 Post-order Divide&Conquer Bottom-up向上傳遞
思路: ?Divide 左右樹醉冤,Conquer求出距l(xiāng)eaf最大距離max_dist 并將其向上傳遞,對應(yīng)添加到result_list
1a寫法先求出了height定躏,建好了固定長度的結(jié)果糠爬。
但其實不用,其實根據(jù)遍歷順序發(fā)現(xiàn)最大距離是若增一定連續(xù)气嫁,所以不用提前建好result_list料睛,每次超過后動態(tài)增加即可府蔗,如寫法2a灾票。
Time Complexity: O(N) Space Complexity: O(N) 遞歸緩存
Solution1a Code:
class Solution {
public List<List<Integer>> findLeaves(TreeNode root) {
// build result list
int height = getMaxHeight(root);
List<List<Integer>> result = new ArrayList<List<Integer>>();
for(int i = 0; i < height; i++) result.add(new ArrayList<Integer>());
// bottom-up dfs
dfsHelper(result, root);
return result;
}
private int dfsHelper(List<List<Integer>> result, TreeNode node) {
if(node == null) return -1;
int max_dist = 1 + Math.max(dfsHelper(result, node.left), dfsHelper(result, node.right));
result.get(max_dist).add(node.val);
return max_dist;
}
private int getMaxHeight(TreeNode root) {
if(root == null) return 0;
return 1 + Math.max(getMaxHeight(root.left), getMaxHeight(root.right));
}
}
Solution2a Code:
class Solution {
public List<List<Integer>> findLeaves(TreeNode root) {
List<List<Integer>> result = new ArrayList<>();
if(root == null) return result;
dfs(root, result);
return result;
}
private int dfs(TreeNode node, List<List<Integer>> result) {
if(node == null) return 0;
int left_d = dfs(node.left, result);
int right_d = dfs(node.right, result);
int level = Math.max(left_d, right_d) + 1;
if(level > result.size()) result.add(new ArrayList<>());
result.get(level - 1).add(node.val);
return level;
}
}