366. Find Leaves of Binary Tree
Given the root
of a binary tree, collect a tree's nodes as if you were doing this:
Collect all the leaf nodes.
Remove all the leaf nodes.
Repeat until the tree is empty.
Example 1:
Input: root = [1,2,3,4,5]
Output: [[4,5,3],[2],[1]]
Explanation:
[[3,5,4],[2],[1]] and [[3,4,5],[2],[1]] are also considered correct answers since per each level it does not matter the order on which elements are returned.
Example 2:
Input: root = [1]
Output: [[1]]
Constraints:
The number of nodes in the tree is in the range
[1, 100]
.-100 <= Node.val <= 100
Solution
Build the materials that we need for topological sorting. - Graph and degree
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public List<List<Integer>> findLeaves(TreeNode root) {
Map<TreeNode, Integer> degree = new HashMap<>();
Map<TreeNode, TreeNode> parents = new HashMap<>();
buildGraph(root, degree, parents);
Queue<TreeNode> queue = new LinkedList<>();
for(TreeNode node : degree.keySet()){
if(degree.get(node) == 0){
queue.add(node);
}
}
List<List<Integer>> ret = new ArrayList<>();
while(!queue.isEmpty()){
int count = queue.size();
List<Integer> temp = new LinkedList<>();
while(count > 0){
TreeNode node = queue.poll();
temp.add(node.val);
TreeNode parent = parents.get(node);
if(parent != null) {
degree.put(parent, degree.get(parent)-1);
if(degree.get(parent) == 0){
queue.add(parent);
}
}
count--;
}
ret.add(temp);
}
return ret;
}
public void buildGraph(TreeNode node, Map<TreeNode,Integer> degree, Map<TreeNode, TreeNode> parents){
if(node == null) return;
int count = 0;
if(node.left != null){
parents.put(node.left, node);
buildGraph(node.left, degree, parents);
count++;
}
if(node.right != null){
parents.put(node.right, node);
buildGraph(node.right, degree, parents);
count++;
}
degree.put(node, count);
}
}
Last updated
Was this helpful?