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.
1function ListNode(val, next = null) {
2 this.val = val;
3 this.next = next;
4}
5
6function TreeNode(val, left = null, right = null) {
7 this.val = val;
8 this.left = left;
9 this.right = right;
10}
11
12function isSubPath(head, root) {
13 if (!root) return false;
14 return dfs(head, root) || isSubPath(head, root.left) || isSubPath(head, root.right);
15}
16
17function dfs(head, root) {
18 if (!head) return true;
19 if (!root) return false;
20 if (head.val !== root.val) return false;
21 return dfs(head.next, root.left) || dfs(head.next, root.right);
22}
The JavaScript solution offers the isSubPath
function and uses dfs
to verify matches for the linked list path starting from current nodes using recursive depth-first traversal.
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
Python solution also adopts an iterative DFS strategy via stack. It uses list of tuples to track the current tree node and linked list node, processing each by stack operations to expand the search iteratively.