23. Linked List in Binary Tree
Last updated
Last updated
Input: head = [4,2,8], root = [1,4,4,null,2,2,null,1,null,6,8,null,null,null,null,1,3]
Output: true
Explanation: Nodes in blue form a subpath in the binary Tree. Input: head = [1,4,2,6], root = [1,4,4,null,2,2,null,1,null,6,8,null,null,null,null,1,3]
Output: trueInput: head = [1,4,2,6,8], root = [1,4,4,null,2,2,null,1,null,6,8,null,null,null,null,1,3]
Output: false
Explanation: There is no path in the binary tree that contains all the elements of the linked list from head.class Solution
{
public:
bool checkPath(TreeNode *root, ListNode *head)
{
if (head == NULL)
{
return true;
}
if (root == NULL)
{
return false;
}
bool res = false;
if (head->val == root->val)
{
res = checkPath(root->left, head->next) || checkPath(root->right, head->next);
}
return res;
}
bool isSubPath(ListNode *head, TreeNode *root)
{
if (root == NULL)
{
return false;
}
if (root->val == head->val)
{
if (checkPath(root, head))
{
return true;
}
}
bool res = isSubPath(head, root->left) || isSubPath(head, root->right);
return res;
}
};