1367. Linked List in Binary Tree
Solution
對每個node進行dfs找出是否符合條件
Time O(N * min(L,H))
Space O(H)
where N = tree size, H = tree height, L = list length.
public boolean isSubPath(ListNode head, TreeNode root) {
if(root == null) return false;
return dfs(head, root) || isSubPath(head, root.left)
|| isSubPath(head, root.right);
}
public boolean dfs(ListNode head, TreeNode node) {
if(head == null) return true;
if(node == null) return false;
if(head.val == node.val){
return dfs(head.next, node.left) || dfs(head.next, node.right);
}
else{
return false;
}
}
Last updated
Was this helpful?