Skip to content

Commit 2a812c3

Browse files
authored
Create leaf-similar-trees.py
1 parent b211554 commit 2a812c3

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

Python/leaf-similar-trees.py

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
# Time: O(n)
2+
# Space: O(h)
3+
4+
# Consider all the leaves of a binary tree.
5+
# From left to right order,
6+
# the values of those leaves form a leaf value sequence.
7+
#
8+
# For example, in the given tree above, the leaf value sequence is (6, 7, 4, 9, 8).
9+
# Two binary trees are considered leaf-similar if their leaf value sequence is the same.
10+
# Return true if and only if the two given trees with head nodes root1 and root2 are leaf-similar.
11+
#
12+
# Note:
13+
# - Both of the given trees will have between 1 and 100 nodes.
14+
15+
import itertools
16+
17+
18+
# Definition for a binary tree node.
19+
class TreeNode(object):
20+
def __init__(self, x):
21+
self.val = x
22+
self.left = None
23+
self.right = None
24+
25+
26+
class Solution(object):
27+
def leafSimilar(self, root1, root2):
28+
"""
29+
:type root1: TreeNode
30+
:type root2: TreeNode
31+
:rtype: bool
32+
"""
33+
def dfs(node):
34+
if not node:
35+
return
36+
if not node.left and not node.right:
37+
yield node.val
38+
for i in dfs(node.left):
39+
yield i
40+
for i in dfs(node.right):
41+
yield i
42+
return all(a == b for a, b in
43+
itertools.izip_longest(dfs(root1), dfs(root2)))

0 commit comments

Comments
 (0)