Problem statement

https://binarysearch.com/problems/Leaf-Equivalent-Trees/

Solution

Equal to Leetcode 0872 Leaf-Similar Trees.

Complexity

Time and space is O(n1 + n2).

Code

class Solution:
    def solve(self, root1, root2):
        nodes = [[], []]
        def dfs(node, ind):
            if not node: return
            if not node.left and not node.right:
                nodes[ind].append(node.val)
            dfs(node.left, ind)
            dfs(node.right, ind)
        
        dfs(root1, 0)
        dfs(root2, 1)
        return nodes[0] == nodes[1]