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]]
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:
[]
题意:
逐层移除二叉树的叶节点。
Solution1: DFS
解本题需要的背景知识: 【height】The height of a node is the number of edges from the node to the deepest leaf.
For instance,
node 1 has height of 2
node 2 has height of 1
node 4 has height of 0
node 5 has height of 0
node 3 has height of 0
Based on the output, we need to gather up all the nodes with height 0, we then gather up all the nodes with height 1, and then all the nodes with height 2
所以我们的target就是边traversal given tree边拿到each node's height, 把不同height的node放到result里
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<List<Integer>> findLeaves(TreeNode root) {
List<List<Integer>> res = new ArrayList<>();
helper(res, root);
return res;
}
//helper function to return the height of current node
private int helper(List<List<Integer>> res, TreeNode root) {
if (root == null) return -1;
int left = helper(res, root.left);
int right = helper(res, root.right);
int height = Math.max(left, right) + 1;
if (res.size() == height) {
res.add(new ArrayList<>());
}
res.get(height).add(root.val);
return height;
}
}