Problem statement

https://leetcode.com/problems/leaf-similar-trees/

Solution

Just traverse both trees with dfs or bfs and compare final lists.

Complexity

Time and space complexity is O(n1 + n2), where n1 and n2 are number of nodes in our trees.

Code

class Solution:
    def leafSimilar(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]