思路:很明显是使用DFS,但是当我使用DFS的时候,竟然有两个用例没有通过
看代码没看出来问题,后来发现当head.val != root.val的时候,跳过了树的当前层,但是链表并没有回到起点,相当于是找树的子序列了,这样遍历下去便不连续了,所以这是错误的
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
boolean flag = false;
public boolean isSubPath(ListNode head, TreeNode root) {
dfs(head,root);
return flag;
}
public void dfs(ListNode head,TreeNode root){
if(head == null){
flag = true;
return;
}
if(root == null){
return;
}
if(head.val == root.val){
dfs(head.next,root.left);
dfs(head.next,root.right);
}else{
dfs(head,root.left);
dfs(head,root.right);
}
}
}
正确的代码:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
boolean flag = false;
public boolean isSubPath(ListNode head, TreeNode root) {
if(root == null) return false;
if(head == null) return true;
if(dfs(head,root)) return true;
return isSubPath(head,root.left) || isSubPath(head,root.right);
}
public boolean dfs(ListNode head,TreeNode root){
if(head == null) return true;
if(root == null) return false;
if(head.val != root.val) return false;
return dfs(head.next,root.left)||dfs(head.next,root.right);
}
}