366. Find Leaves of Binary Tree
Find Leaves of Binary Tree
Last updated
Find Leaves of Binary Tree
Last updated
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public List<List<Integer>> findLeaves(TreeNode root) {
if (root == null) return new ArrayList<>();
if (root.left == null && root.right == null) {
List<Integer> current = new ArrayList<>();
current.add(root.val);
List<List<Integer>> result = new ArrayList<>();
result.add(current);
return result;
}
List<List<Integer>> left = findLeaves(root.left);
List<List<Integer>> right = findLeaves(root.right);
if (left.size() < right.size()) {
List<List<Integer>> temp = right;
right = left;
left = temp;
}
for (int i = 0; i < right.size(); i++) {
left.get(i).addAll(right.get(i));
}
List<Integer> current = new ArrayList<>();
current.add(root.val);
left.add(current);
return left;
}
}