Leetcode 366 Solution
This article provides solution to leetcode question 366 (find-leaves-of-binary-tree)
Access this page by simply typing in "lcs 366" in your browser address bar if you have bunnylol configured.
Leetcode Question Link
https://leetcode.com/problems/find-leaves-of-binary-tree
Solution
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
map<int, vector<int>> a;
public:
int doFindLeaves(TreeNode* root)
{
if (root == NULL)
return 0;
int left_depth = doFindLeaves(root->left);
int right_depth = doFindLeaves(root->right);
int depth = max(left_depth, right_depth);
a[depth].push_back(root->val);
return depth + 1;
}
vector<vector<int>> findLeaves(TreeNode* root) {
doFindLeaves(root);
vector<vector<int>> res;
for (auto pair : a)
res.push_back(pair.second);
return res;
}
};