Python 1367.py
class Solution:
def isSubPath(self, head: Optional[ListNode], root: Optional[TreeNode]) -> bool:
def match(lis, tre):
if not lis:
return True
if not tre:
return False
if lis.val != tre.val:
return False
return match(lis.next, tre.left) or match(lis.next, tre.right)
def deeper(node):
if not node:
return False
if match(head, node):
print(node.val)
return True
return deeper(node.left) or deeper(node.right)
return deeper(root)
Difficulty
and has an acceptance rate of about 52% (400k+ submissions).
Typical patterns to solve this problem:
- Binary Tree
- Depth First Search
- Linked List
- Tree
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation defines a Solution class with a single public method isSubPath. The method determines whether a singly-linked list, represented by head, appears as a downward path in a binary tree rooted at root. The algorithm proceeds by recursively searching every tree node as a potential starting point and, for each candidate, attempts to match the list sequentially along left or right child edges.
Core Logic
The solution is built around two nested helper functions: match and deeper.
match - sequential list-to-tree comparison
def match(lis, tre):
if not lis:
return True
if not tre:
return False
if lis.val != tre.val:
return False
return match(lis.next, tre.left) or match(lis.next, tre.right)
match receives a list node lis and a tree node tre.
The base case if not lis: return True captures the situation where the entire list has been consumed, indicating a successful match regardless of remaining tree structure.
The second base case if not tre: return False handles the scenario where the list still has elements but the tree path has terminated, preventing a false positive.
A value mismatch if lis.val != tre.val: return False aborts the current path early.
If the current values agree, the function recurses on the next list node while exploring both left and right child branches of the current tree node. This dual-branch recursion enables the list to follow any downward direction at each step.
deeper - exhaustive tree traversal
def deeper(node):
if not node:
return False
if match(head, node):
print(node.val)
return True
return deeper(node.left) or deeper(node.right)
deeper walks the entire tree. The early exit if not node: return False stops recursion at null subtrees.
When a node is encountered, match(head, node) is invoked to test whether the list begins at that node. A diagnostic print(node.val) is executed only when a successful match is found, providing a trace of the matching tree node’s value.
If the current node does not start a matching path, deeper continues recursively on the left and right children, ensuring that every possible starting position is examined.
Public entry point
return deeper(root)
The method simply launches the exhaustive search from the root of the tree.
Edge Cases Handled
When the linked list is empty (head is None), the first call to match immediately satisfies if not lis: return True, causing deeper to return True for any tree, including an empty tree. This correctly reflects that an empty list is trivially a sub-path of any tree.
If the binary tree is empty (root is None) while the list is non-empty, deeper returns False because the initial null check prevents any further processing.
When the list length exceeds the depth of any branch in the tree, the if not tre: return False guard in match stops the recursion as soon as the tree path ends, preventing out-of-bounds accesses.
The algorithm also tolerates trees with duplicate values. Because match explores both left and right branches at each step, it can follow any combination of directions that aligns with the list, even when multiple child nodes share the same value as the current list element.
Implicit Performance Optimizations
The implementation avoids unnecessary object creation or data copying; it works directly with the original list and tree nodes.
The early-return checks in match (if not lis and if not tre) prune the recursion tree as soon as a definitive outcome is known, reducing the number of recursive calls.
By placing the match invocation before the recursive descent in deeper, the algorithm attempts a full list match at the current node before exploring deeper subtrees. This ordering can short-circuit the search when a match is found high in the tree, avoiding the cost of traversing the remainder of the structure.
The use of logical or in both helper functions ensures short-circuit evaluation: once a successful path is discovered, subsequent recursive branches are not evaluated, saving time in favorable cases.
Overall Flow
The isSubPath method initiates a depth-first traversal of the binary tree via deeper. At each visited node, it attempts to align the linked list with a downward path using match. Successful alignment triggers a print of the matching node’s value and propagates True back up the call stack, causing the overall method to return True. If no alignment succeeds after the entire tree has been examined, the method returns False.
ELI5 - Simplified Explanation
Imagine a giant tree made of little light bulbs that branches out in many directions. There is also a long, wiggly line of beads. The goal is to find if the line of beads is hidden somewhere inside the tree branches.
To do this, the computer looks at every single spot in the tree. It picks one spot and starts comparing it to the first bead on the line. If the color of the bead matches the light bulb, it keeps going to the next bead and the next bulb. It follows the branches downward to see if the whole line of beads fits perfectly along one of those paths.
If the beads do not match the bulbs at a starting spot, the computer does not get sad. It simply moves to the next light bulb in the tree and starts the process again. It repeats this over and over for every single bulb until it finally finds the right path that holds the entire line of beads in the exact same order. If it reaches the end of the line of beads while following the branches, that means the line exists inside the tree.
Code Quality
Complexity Analysis
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | |||||||||
|---|---|---|---|---|---|---|---|---|---|
| author | solutions | ||||||||
| www | AlgoMonster | C++ | Python | Java | TS | ||||
| WalkCCC | C++ | Python | Java | ||||||
| leetcode.ca | C++ | Python | Java | Go | Rust | TS | |||
| Progiez | C++ | Python | Java | ||||||
| github | black-shadows | C++ | |||||||
| charles-wangkai | Java | ||||||||
| everthis | JS | ||||||||
| fartem | Ruby | ||||||||
| fsq | C++ | ||||||||
| JoshCrozier | JS | ||||||||
| lkwq007 | Python | ||||||||
| varunu28 | Java | ||||||||
| wisdompeak | C++ | ||||||||
| YuriSpiridonov | Python | ||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||
| WalkCCC | C++, Python, Java | ||||||||
| leetcode.ca | C++, Go, Java, Python, Rust, TypeScript | ||||||||
| Progiez | C++, Java, Python | ||||||||
| black-shadows | C++, C++ | ||||||||
| charles-wangkai | Java | ||||||||
| everthis | JavaScript | ||||||||
| fartem | Ruby | ||||||||
| fsq | C++ | ||||||||
| JoshCrozier | JavaScript | ||||||||
| lkwq007 | Python | ||||||||
| varunu28 | Java | ||||||||
| wisdompeak | C++ | ||||||||
| YuriSpiridonov | Python |
Videos
Solved On The Same Day
- problem 1365: How Many Numbers Are Smaller Than the Current Number
- problem 1389: Create Target Array in the Given Order
- problem 1394: Find Lucky Integer in an Array
- problem 1758: Minimum Changes To Make Alternating Binary String
- problem 1357: Apply Discount Every n Orders
- problem 1362: Closest Divisors
- problem 1386: Cinema Seat Allocation
- problem 1390: Four Divisors
- problem 1395: Count Number of Teams
- problem 1759: Count Number of Homogenous Substrings
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality