leetcode 872. Leaf-Similar Trees (Python)

872. Leaf-Similar Trees (Python)

Depth-First-Search. Tree.

Description

Consider all the leaves of a binary tree. From left to right order, the values of those leaves form a leaf value sequence.

tree

For example, in the given tree above, the leaf value sequence is (6, 7, 4, 9, 8).

Two binary trees are considered leaf-similar if their leaf value sequence is the same.

Return true if and only if the two given trees with head nodes root1 and root2 are leaf-similar.

Constraints:

  • Both of the given trees will have between 1 and 200 nodes.
  • Both of the given trees will have values between 0 and 200

Methodology

Use DFS to find both trees’ leaf and append the leaf into array. Compare two arrays if they are equal then two trees are leaf-similar otherwise return false

Code

def leafSimilar(self, root1: TreeNode, root2: TreeNode) -> bool:
        def findLeaf(root, leaf_seq):
            if not root: return
            if not root.left and not root.right:
                leaf_seq.append(root.val)
            findLeaf(root.left, leaf_seq)
            findLeaf(root.right, leaf_seq)
            return leaf_seq
        root1_leaf=findLeaf(root1, [])
        root2_leaf=findLeaf(root2, [])
        return root1_leaf == root2_leaf

BigO

Time complexity: O(n) where n is the number of the nodes of both trees.

Search

    Table of Contents