forked from Kyrylo-Ktl/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLeaf-Similar Trees.py
More file actions
31 lines (24 loc) · 851 Bytes
/
Leaf-Similar Trees.py
File metadata and controls
31 lines (24 loc) · 851 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
from itertools import zip_longest
from typing import Optional
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
"""
Time: O(H)
Memory: O(H)
"""
def leafSimilar(self, first: Optional[TreeNode], second: Optional[TreeNode]) -> bool:
return all(x == y for x, y in zip_longest(self._get_leaves(first), self._get_leaves(second)))
@classmethod
def _get_leaves(cls, tree: Optional[TreeNode]):
if tree is not None:
if cls.is_leaf(tree):
yield tree.val
yield from cls._get_leaves(tree.left)
yield from cls._get_leaves(tree.right)
@staticmethod
def is_leaf(node: TreeNode) -> bool:
return node.left is None and node.right is None