1367-Linked-List-in-Binary-Tree
Last updated
Last updated
/**
* 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;
}
//因为我们不知道从哪一个节点开始匹配,所以我们首先从根节点开始,如果从根节点开始匹配不成功,那么我们会回溯到
//第一次还未进入递归函数的位置,这里head又是指向链表的头节点的,所以我们根本不用操作匹配到一半失败怎么办
//这样会递归执行isSubPath从节点的左右子节点开始匹配,不行的话又会从下一节点的左右字节点开始匹配
return recur(head,root)|| isSubPath(head,root.left)|| isSubPath(head,root.right);
}
private boolean recur(ListNode head,TreeNode root){
if(head==null){
return true;
}
if(root==null){
return false;
}
if(head.val !=root.val){
return false;
}
return recur(head.next,root.left)|| recur(head.next,root.right);
}
}