Lunski's Clutter

This is a place to put my clutters, no matter you like it or not, welcome here.

0%

366. Find Leaves of Binary Tree

Given a binary tree, collect a tree’s nodes as if you were doing this: Collect and remove all leaves, repeat until the tree is empty.

Example:

1
2
3
4
5
6
7
8
9
Input: [1,2,3,4,5]

1
/ \
2 3
/ \
4 5

Output: [[4,5,3],[2],[1]]

Explanation:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
1. Removing the leaves [4,5,3] would result in this tree:

1
/
2


2. Now removing the leaf [2] would result in this tree:

1


3. Now removing the leaf [1] would result in the empty tree:

[]
TC: O(n), SC: O(n)
class Solution(object):
    ans = []
    def findLeaves(self, root):
        dfs(root)
        return self.ans

    def dfs(root):
        if not root:
            return 0
        left = dfs(root.left)
        right = dfs(root.right)
        depth = max(left, right)
        if depth == len(ans):
            self.ans.append([root.val])
        else:
            self.ans[-1].append(root.val)
        return depth+1

如果你覺得這篇文章很棒,請你不吝點讚 (゚∀゚)

Welcome to my other publishing channels