366. Find Leaves of Binary Tree - cocoder39/coco39_LC GitHub Wiki
366. Find Leaves of Binary Tree
converting to find hight of each node, then grouping by height
class Solution:
def findLeaves(self, root: Optional[TreeNode]) -> List[List[int]]:
res = []
self.getHeight(root, res)
return res
def getHeight(self, root: Optional[TreeNode], res: List[List[int]]) -> int:
if not root:
return -1
height = max(self.getHeight(root.left, res), self.getHeight(root.right, res)) + 1
if len(res) == height:
res.append([])
res[height].append(root.val)
return height
==================================================
O(n) time and O(height) space
class Solution {
public:
vector<vector<int>> findLeaves(TreeNode* root) {
vector<vector<int>> res;
helper(res, root);
return res;
}
private:
int helper(vector<vector<int>>& res, TreeNode* root) {
if (! root) {
return 0;
}
int level = max(helper(res, root->left), helper(res, root->right)) + 1;
if (res.size() < level)
res.push_back(vector<int>());
res[level - 1].push_back(root->val);
return level;
}
};