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.
1#include <stdbool.h>
2#include <stddef.h>
3
4struct ListNode {
5 int val;
6 struct ListNode *next;
7};
8
9struct TreeNode {
10 int val;
11 struct TreeNode *left;
12 struct TreeNode *right;
13};
14
15bool isSubPathFromNode(struct ListNode* head, struct TreeNode* root) {
16 if (!head) return true;
17 if (!root) return false;
18 if (head->val != root->val) return false;
19 return isSubPathFromNode(head->next, root->left) || isSubPathFromNode(head->next, root->right);
20}
21
22bool isSubPath(struct ListNode* head, struct TreeNode* root) {
23 if (!root) return false;
24 if (isSubPathFromNode(head, root)) return true;
25 return isSubPath(head, root->left) || isSubPath(head, root->right);
26}
We define a helper function isSubPathFromNode
to check if a given node in the binary tree can serve as the starting point of a subpath that matches the linked list. It performs a depth-first search recursively. If the current list node matches the tree node, it calls itself on the next list node with both children.
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.