LeetCode 1367. Linked List in Binary Tree
Given a binary tree and a linkedlist, check if there is a path or subpath(downward) in this tree which contains the same value as given linkedlist.
and pay attention: the binary tree nodes may contains some duplicate values.
idea:
 the first thing come to my mind is String matching, make be we can solve this using one of those algorithms, like KMP
 we need to get all the path and check if the linkedlist is the subpath of any of those paths.
double recursion, magnificant!!
 the main idea is: iterate each node, and checking if it is working with current node to start with linkedlist.
class Solution {
    public boolean isSubPath(ListNode head, TreeNode root) {
        
        if (root == null) return false;
        if (check(root, head)) {
            return true;
        }
        return isSubPath(head, root.left) || isSubPath(head, root.right); //this recrusion will checking every node as the start
        
    }
    
    private boolean check(TreeNode root, ListNode head) { //this will checking with "root" as the start to compare with linkedlist
        if (head == null) return true;
        if (root == null) return false;
        if (root.val != head.val) return false;
        return check(root.left, head.next) || check(root.right, head.next);
    }
}
                
                    
                
                
            
        
浙公网安备 33010602011771号