题目:
给你一棵以 root 为根的二叉树和一个 head 为第一个节点的链表。
如果在二叉树中,存在一条一直向下的路径,且每个点的数值恰好一一对应以 head 为首的链表中每个节点的值,那么请你返回 True ,否则返回 False 。
一直向下的路径的意思是:从树中某个节点开始,一直连续向下的路径。
思路:
递归判断该二叉树点为起点是否符合与二叉树的两个子节点为起点是否符合
递归结束条件为链表递归完成。
class Solution {
public boolean isSubPath(ListNode head, TreeNode root) {
if(head==null) return true;
if(root==null) return false;
return helper(head,root)||isSubPath(head,root.left)||isSubPath(head,root.right);
}
public boolean helper(ListNode cur,TreeNode root){
if(cur==null) return true;
if(root==null) return false;
if(root.val!=cur.val) return false;
return helper(cur.next,root.left)||helper(cur.next,root.right);
}
}