LeetCode 1367
2020.8.13
我的通过代码
/**
* 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 {
public boolean isSubPath(ListNode head, TreeNode root) {
if(head==null) return true;
if(root==null) return false;
return judge(head,root)||isSubPath(head,root.left)||isSubPath(head,root.right);
}
boolean judge(ListNode head, TreeNode root) {
if(head==null) return true;
if(root==null) return false;
if(head.val!=root.val) return false;
else {
return judge(head.next,root.left)||judge(head.next,root.right);
}
}
}
碰上的问题
这次出现的问题应该是很典型的递归问题,一开始我写的代码是这样的:
/**
* 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 {
public boolean isSubPath(ListNode head, TreeNode root) {
if(head==null) return true;
if(root==null) return false;
if(head.val==root.val) {
return isSubPath(head.next,root.left)||isSubPath(head.next,root.right);
} else {
return isSubPath(head,root.left)||isSubPath(head,root.right);
}
}
}
看起来很有道理,但还是忽略了一些情况,没有办法让二叉树的每一个节点都有作为头节点的机会,举个例子:
[1,2,1,2,4]
[1,null,2,null,1,null,2,null,1,null,2,null,4]
这样一棵只有左子树的二叉树,前四个节点都可以与链表的前四个元素匹配,可程序发现最后一个节点的值1不等于链表的最后一个节点的值4时,程序已经无法再回到二叉树的第二个节点了,只能从第五个节点开始继续往下匹配,这样一来就漏掉了好多可能性,少了很多情况,导致最后的结果不正确。