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
Solutions
Solution 1
1 2 3 4 5 6 7 8 9101112131415161718192021
# Definition for a binary tree node.# class TreeNode:# def __init__(self, val=0, left=None, right=None):# self.val = val# self.left = left# self.right = rightclassSolution:deffindLeaves(self,root:Optional[TreeNode])->List[List[int]]:defdfs(root:Optional[TreeNode])->int:ifrootisNone:return0l,r=dfs(root.left),dfs(root.right)h=max(l,r)iflen(ans)==h:ans.append([])ans[h].append(root.val)returnh+1ans=[]dfs(root)returnans
/** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */funcfindLeaves(root*TreeNode)(ans[][]int){vardfsfunc(*TreeNode)intdfs=func(root*TreeNode)int{ifroot==nil{return0}l,r:=dfs(root.Left),dfs(root.Right)h:=max(l,r)iflen(ans)==h{ans=append(ans,[]int{})}ans[h]=append(ans[h],root.Val)returnh+1}dfs(root)return}