|
| 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