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 int val;
3 ListNode next;
4 ListNode(int x) { val = x; next = null; }
5}
6
7class TreeNode {
8 int val;
9 TreeNode left;
10 TreeNode right;
11 TreeNode(int x) { val = x; }
12}
13
14public class Solution {
15 public boolean isSubPath(ListNode head, TreeNode root) {
16 if (root == null) return false;
17 return dfs(head, root) || isSubPath(head, root.left) || isSubPath(head, root.right);
18 }
19
20 private boolean dfs(ListNode head, TreeNode root) {
21 if (head == null) return true;
22 if (root == null) return false;
23 if (head.val != root.val) return false;
24 return dfs(head.next, root.left) || dfs(head.next, root.right);
25 }
26}
The Java solution uses similar DFS logic. The main function isSubPath
and helper dfs
navigate through the tree to find a path that matches the linked list nodes.
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
Java implements iterative DFS with a stack approach, leveraging the Pair class to store tree and list node relationships. This facilitates stack-driven traversal, exploring nodes iteratively for list path matching.