Skip to content

Latest commit

 

History

History
58 lines (44 loc) · 1.39 KB

872.md

File metadata and controls

58 lines (44 loc) · 1.39 KB

Leaf-Similar Trees

Description

link


Solution

  • See Code

Code

Complexity T : O(N) M : O(n)

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def leafSimilar(self, root1: TreeNode, root2: TreeNode) -> bool:
        def get_leafs(root):
            if not root.left and not root.right:
                return [root.val]
            if root.left and root.right:
                return get_leafs(root.left) + get_leafs(root.right)
            elif root.left:
                return get_leafs(root.left)
            else:
                return get_leafs(root.right)
        return get_leafs(root1) == get_leafs(root2)



# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def leafSimilar(self, root1: TreeNode, root2: TreeNode) -> bool:
        def get_leafs(root):
            if not root: return
            if not root.left and not root.right:
                yield root.val
            yield from get_leafs(root.left)
            yield from get_leafs(root.right)
        return all( a == b for a, b in zip_longest(get_leafs(root1), get_leafs(root2)))