Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 3265363

Browse files
Create leaf_similar_trees.py
1 parent fac7140 commit 3265363

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed

‎day-25/leaf_similar_trees.py‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
# Problem: Leaf-Similar Trees
2+
# Link: https://leetcode.com/problems/leaf-similar-trees/description/
3+
# Tags: Tree, DFS, Stack
4+
# Approach: Collect the leaf sequence of each tree by a DFS that appends node values
5+
# only when a node is a leaf (no children). Compare the two sequences for equality.
6+
# This isolates order and values of leaves regardless of internal structure.
7+
# Time Complexity: O(n + m) – visit each node of both trees once
8+
# Space Complexity: O(h1 + h2) – recursion/stack depth for both trees (plus leaf lists)
9+
10+
11+
class Solution:
12+
def leafSimilar(self, root1, root2):
13+
def leaves(root, out):
14+
if not root:
15+
return
16+
if not root.left and not root.right:
17+
out.append(root.val)
18+
return
19+
leaves(root.left, out)
20+
leaves(root.right, out)
21+
22+
a, b = [], []
23+
leaves(root1, a)
24+
leaves(root2, b)
25+
return a == b

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /