|
| 1 | +QUESTION : |
| 2 | +Given a binary tree root and a linked list with head as the first node. |
| 3 | +Return True if all the elements in the linked list starting from the head correspond to some downward path connected in the binary tree otherwise return False. |
| 4 | +In this context downward path means a path that starts at some node and goes downwards. |
| 5 | + |
| 6 | +Example 1: |
| 7 | +Input: head = [4,2,8], root = [1,4,4,null,2,2,null,1,null,6,8,null,null,null,null,1,3] |
| 8 | +Output: true |
| 9 | +Explanation: Nodes in blue form a subpath in the binary Tree. |
| 10 | + |
| 11 | +Example 2: |
| 12 | +Input: head = [1,4,2,6], root = [1,4,4,null,2,2,null,1,null,6,8,null,null,null,null,1,3] |
| 13 | +Output: true |
| 14 | + |
| 15 | +Example 3: |
| 16 | +Input: head = [1,4,2,6,8], root = [1,4,4,null,2,2,null,1,null,6,8,null,null,null,null,1,3] |
| 17 | +Output: false |
| 18 | +Explanation: There is no path in the binary tree that contains all the elements of the linked list from head. |
| 19 | + |
| 20 | +Constraints: |
| 21 | +1 <= node.val <= 100 for each node in the linked list and binary tree. |
| 22 | +The given linked list will contain between 1 and 100 nodes. |
| 23 | +The given binary tree will contain between 1 and 2500 nodes. |
| 24 | + |
| 25 | +C++ SOLUTION : |
| 26 | + |
| 27 | +class Solution { |
| 28 | +public: |
| 29 | + bool isSubPath(ListNode* head, TreeNode* root) { |
| 30 | + if(root){ |
| 31 | + if(isEqual(head, root)){ |
| 32 | + return true; |
| 33 | + } |
| 34 | + return isSubPath(head, root->left) || isSubPath(head, root->right); |
| 35 | + } |
| 36 | + return false; |
| 37 | + } |
| 38 | + bool isEqual(ListNode* head, TreeNode* root){ |
| 39 | + if(!head){ |
| 40 | + return true; |
| 41 | + } |
| 42 | + if(!root){ |
| 43 | + return false; |
| 44 | + } |
| 45 | + return head->val == root->val && (isEqual(head->next, root->left) || isEqual(head->next, root->right)); |
| 46 | + } |
| 47 | +}; |
| 48 | + |
| 49 | +PYTHON SOLUTION : |
| 50 | + |
| 51 | +def isSubPath(self, head: ListNode, root: TreeNode) -> bool: |
| 52 | + target = "" |
| 53 | + while head: |
| 54 | + target = target + str(head.val) |
| 55 | + head = head.next |
| 56 | + |
| 57 | + def dfs(root, path): |
| 58 | + if target in path: |
| 59 | + return True |
| 60 | + |
| 61 | + if root.left: |
| 62 | + ans = dfs(root.left, path + str(root.left.val)) |
| 63 | + if ans == True: |
| 64 | + return True |
| 65 | + |
| 66 | + if root.right: |
| 67 | + ans = dfs(root.right, path + str(root.right.val)) |
| 68 | + if ans == True: |
| 69 | + return True |
| 70 | + |
| 71 | + return False |
| 72 | + |
| 73 | + return dfs(root, str(root.val)) |
0 commit comments