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
public class ListNode {
public int val;
public ListNode next;
public ListNode(int x) { val = x; next = null; }
}
public class TreeNode {
public int val;
public TreeNode left;
public TreeNode right;
public TreeNode(int x) { val = x; }
}
public class Solution {
public bool IsSubPath(ListNode head, TreeNode root) {
var stack = new Stack<(TreeNode, ListNode)>();
stack.Push((root, head));
while (stack.Count > 0) {
var (treeNode, listNode) = stack.Pop();
if (listNode == null) return true;
if (treeNode == null) continue;
if (treeNode.val == listNode.val) {
stack.Push((treeNode.left, listNode.next));
stack.Push((treeNode.right, listNode.next));
}
if (listNode.next != null) {
stack.Push((treeNode.left, listNode));
stack.Push((treeNode.right, listNode));
}
}
return false;
}
}
For C#, the iterative DFS utilizes a stack for examination of the tree nodes in combination with the linked list nodes. Here, Tuple-like stack entries facilitate organized, orderly management of pairings.