Skip to main content

366 - Find Leaves of Binary Tree

Details

KeyValue
Linkhttps://leetcode.com/problems/find-leaves-of-binary-tree/
LanguagePython 3
Runtime26 ms, faster than 98.90% of Python3 online submissions for Find Leaves of Binary Tree
Memory Usage13.8 MB, less than 98.46% of Python3 online submissions for Find Leaves of Binary Tree
DatastructuresTreeNode
AlgorithmsDFS (postorder)
ComplexityTime: O(NlogN) Memory: O(N)

Procedure

  1. ...

Code

# 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 = right
class Solution:
def findLeaves(self, root: Optional[TreeNode]) -> List[List[int]]:
result = []

def dfs(r):
if r == None: return -1
nonlocal result
distance = max(dfs(r.left), dfs(r.right)) + 1
if distance >= len(result):
result.append([r.val])
else:
result[distance].append(r.val)
return distance

dfs(root)
return result