LeetCode Solutions
366. Find Leaves of Binary Tree
Time: $O(n)$ Space: $O(h)$
class Solution {
public:
vector<vector<int>> findLeaves(TreeNode* root) {
vector<vector<int>> ans;
depth(root, ans);
return ans;
}
private:
// Depth of root (0-indexed)
int depth(TreeNode* root, vector<vector<int>>& ans) {
if (root == nullptr)
return -1;
const int l = depth(root->left, ans);
const int r = depth(root->right, ans);
const int h = 1 + max(l, r);
if (ans.size() == h) // Meet leaf
ans.push_back({});
ans[h].push_back(root->val);
return h;
}
};
class Solution {
public List<List<Integer>> findLeaves(TreeNode root) {
List<List<Integer>> ans = new ArrayList<>();
depth(root, ans);
return ans;
}
// Depth of root (0-indexed)
private int depth(TreeNode root, List<List<Integer>> ans) {
if (root == null)
return -1;
final int l = depth(root.left, ans);
final int r = depth(root.right, ans);
final int h = 1 + Math.max(l, r);
if (ans.size() == h) // Meet leaf
ans.add(new ArrayList<>());
ans.get(h).add(root.val);
return h;
}
}