1367 - Linked List in Binary Tree
JAVA
class Solution {
public boolean isSubPath(ListNode head, TreeNode root) {
if (root == null) {
return false;
}
return dfs(head, root) || isSubPath(head, root.left) || isSubPath(head, root.right);
}
private boolean dfs(ListNode head, TreeNode root) {
if (head == null) {
return true;
}
if (root == null || head.val != root.val) {
return false;
}
return dfs(head.next, root.left) || dfs(head.next, root.right);
}
}C++
class Solution {
public:
bool isSubPath(ListNode* head, TreeNode* root) {
if (!root) {
return false;
}
return dfs(head, root) || isSubPath(head, root->left) || isSubPath(head, root->right);
}
bool dfs(ListNode* head, TreeNode* root) {
if (!head) {
return true;
}
if (!root || head->val != root->val) {
return false;
}
return dfs(head->next, root->left) || dfs(head->next, root->right);
}
};
Comments
Post a Comment