Skip to content

Commit 16d7665

Browse files
committed
[LeetCode Sync] Runtime - 0 ms (100.00%), Memory - 17.7 MB (94.25%)
1 parent bf7a199 commit 16d7665

File tree

2 files changed

+56
-0
lines changed

2 files changed

+56
-0
lines changed
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
<p>Consider all the leaves of a binary tree, from&nbsp;left to right order, the values of those&nbsp;leaves form a <strong>leaf value sequence</strong><em>.</em></p>
2+
3+
<p><img alt="" src="https://s3-lc-upload.s3.amazonaws.com/uploads/2018/07/16/tree.png" style="width: 400px; height: 336px;" /></p>
4+
5+
<p>For example, in the given tree above, the leaf value sequence is <code>(6, 7, 4, 9, 8)</code>.</p>
6+
7+
<p>Two binary trees are considered <em>leaf-similar</em>&nbsp;if their leaf value sequence is the same.</p>
8+
9+
<p>Return <code>true</code> if and only if the two given trees with head nodes <code>root1</code> and <code>root2</code> are leaf-similar.</p>
10+
11+
<p>&nbsp;</p>
12+
<p><strong class="example">Example 1:</strong></p>
13+
<img alt="" src="https://assets.leetcode.com/uploads/2020/09/03/leaf-similar-1.jpg" style="width: 600px; height: 237px;" />
14+
<pre>
15+
<strong>Input:</strong> root1 = [3,5,1,6,2,9,8,null,null,7,4], root2 = [3,5,1,6,7,4,2,null,null,null,null,null,null,9,8]
16+
<strong>Output:</strong> true
17+
</pre>
18+
19+
<p><strong class="example">Example 2:</strong></p>
20+
<img alt="" src="https://assets.leetcode.com/uploads/2020/09/03/leaf-similar-2.jpg" style="width: 300px; height: 110px;" />
21+
<pre>
22+
<strong>Input:</strong> root1 = [1,2,3], root2 = [1,3,2]
23+
<strong>Output:</strong> false
24+
</pre>
25+
26+
<p>&nbsp;</p>
27+
<p><strong>Constraints:</strong></p>
28+
29+
<ul>
30+
<li>The number of nodes in each tree will be in the range <code>[1, 200]</code>.</li>
31+
<li>Both of the given trees will have values in the range <code>[0, 200]</code>.</li>
32+
</ul>
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
# Definition for a binary tree node.
2+
# class TreeNode:
3+
# def __init__(self, val=0, left=None, right=None):
4+
# self.val = val
5+
# self.left = left
6+
# self.right = right
7+
class Solution:
8+
def leafSimilar(self, root1: Optional[TreeNode], root2: Optional[TreeNode]) -> bool:
9+
def dfs(root: Optional[TreeNode], arr):
10+
if root.left == root.right:
11+
arr.append(root.val)
12+
return
13+
14+
if root.left:
15+
dfs(root.left, arr)
16+
if root.right:
17+
dfs(root.right, arr)
18+
19+
arr1 = []
20+
arr2 = []
21+
dfs(root1, arr1)
22+
dfs(root2, arr2)
23+
return arr1 == arr2
24+

0 commit comments

Comments
 (0)