Sponsored
Sponsored
This approach utilizes depth-first search (DFS) recursively to search through the binary tree. For each node that matches the head of the linked list, we will try to match the remaining nodes of the linked list with the children nodes of the current tree node.
Time Complexity: O(n * m), where n is the number of tree nodes and m is the number of list nodes. Space Complexity: O(h), where h is the height of the tree, due to recursion stack usage.
1class ListNode:
2 def __init__(self, val=0, next=None):
3 self.val = val
4 self.next = next
5
6class TreeNode:
7 def __init__(self, val=0, left=None, right=None):
8 self.val = val
9 self.left = left
10 self.right = right
11
12class Solution:
13 def isSubPath(self, head: ListNode, root: TreeNode) -> bool:
14 if not root:
15 return False
16 return self.dfs(head, root) or self.isSubPath(head, root.left) or self.isSubPath(head, root.right)
17
18 def dfs(self, head: ListNode, root: TreeNode) -> bool:
19 if not head:
20 return True
21 if not root:
22 return False
23 if head.val != root.val:
24 return False
25 return self.dfs(head.next, root.left) or self.dfs(head.next, root.right)
The Python version of the solution uses recursive DFS. The function isSubPath
determines starting points for matching the linked list's path in the tree using the helper method dfs
.
This strategy employs an iterative depth-first search using an explicit stack to avoid recursion-driven call stacks. We simulate the recursive call stack with a custom stack structure, effectively managing process states iteratively as we check for potential subpaths.
Time Complexity: O(n * m), Space Complexity: O(n), where n is the number of nodes in the tree and m is the list node count due to stack usage.
1
Using an explicit stack to simulate recursion, this C solution handles the depth-first search iteratively. Each stack element consists of a tree node and the matching list node associated with that state. We continuously pop from the stack, testing elements.