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].
/** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */funcfindLeaves(root*TreeNode)[][]int{prev:=&TreeNode{Val:0,Left:root,Right:nil,}varres[][]intforprev.Left!=nil{vart[]intdfs(prev.Left,prev,&t)res=append(res,t)}returnres}funcdfs(root,prev*TreeNode,t*[]int){ifroot==nil{return}ifroot.Left==nil&&root.Right==nil{*t=append(*t,root.Val)ifprev.Left==root{prev.Left=nil}else{prev.Right=nil}}dfs(root.Left,root,t)dfs(root.Right,root,t)}