二叉树中的链表
给你一棵以 root 为根的二叉树和一个 head 为第一个节点的链表。
如果在二叉树中,存在一条一直向下的路径,且每个点的数值恰好一一对应以 head 为首的链表中每个节点的值,那么请你返回 True ,否则返回 False 。
一直向下的路径的意思是:从树中某个节点开始,一直连续向下的路径。

public boolean isSubPath(ListNode head, TreeNode root) {
if (root == null)
return false;
return isSubPathFromRoot(head, root)
|| isSubPath(head, root.left)
|| isSubPath(head, root.right);
}
//从根节点开始向下找
private boolean isSubPathFromRoot(ListNode head, TreeNode root) {
if (head == null)
return true;
if (root == null)
return false;
if (root.val == head.val)
return isSubPathFromRoot(head.next, root.left) || isSubPathFromRoot(head.next, root.right);
return false;
}
浙公网安备 33010602011771号