Given the root of a binary tree, collect a tree's nodes as if you were doing this:
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:
[1, 100].-100 <= Node.val <= 100class Solution:
def findLeaves(self, root: Optional[TreeNode]) -> List[List[int]]:
self.pairs = []
def getHeight(node):
if node is None:
return -1
# first calculate the height of the left and right children
leftHeight = getHeight(node.left)
rightHeight = getHeight(node.right)
# based on the height of the left and right children, obtain the height of the current (parent) node
currHeight = max(leftHeight, rightHeight) + 1
# collect the pair -> (height, val)
self.pairs.append((currHeight, node.val))
# return the height of the current node
return currHeight
getHeight(root)
# sort all the (height, val) pairs
self.pairs.sort(key=lambda p: p[0])
n = len(self.pairs)
height = 0
i = 0
solution = []
while i < n:
nums = []
while i < n and self.pairs[i][0] == height:
nums.append(self.pairs[i][1])
i += 1
solution.append(nums)
height += 1
return solutionWhere is the total number of nodes in the binary tree
class Solution:
def findLeaves(self, root: Optional[TreeNode]) -> List[List[int]]:
self.solution = []
def getHeight(node):
if node is None:
return -1
leftHeight = getHeight(node.left)
rightHeight = getHeight(node.right)
currHeight = max(leftHeight, rightHeight) + 1
if len(self.solution) == currHeight:
self.solution.append([])
self.solution[currHeight].append(node.val)
return currHeight
getHeight(root)
return self.solutionWhere is the total number of nodes in the binary tree