1367.二叉树中的列表
给你一棵以 root 为根的二叉树和一个 head 为第一个节点的链表。
如果在二叉树中,存在一条一直向下的路径,且每个点的数值恰好一一对应以 head 为首的链表中每个节点的值,那么请你返回 True ,否则返回 False 。
一直向下的路径的意思是:从树中某个节点开始,一直连续向下的路径。
思路:dfs
/**
* 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 check(head, root) || isSubPath(head, root.left) || isSubPath(head, root.right);
}
public boolean check(ListNode head, TreeNode node) {
//递归结束条件1:链表走完了,返回true
if(head == null) {
return true;
}
//递归结束条件2:链表没走完,树走完了(到达叶子结点),这肯定不行,返回false
if(node == null) {
return false;
}
//如果链表节点值和路径节点值不同,必定不是啊
if(head.val != node.val) {
return false;
}
//head.val == node.val
//如果值相同,继续看树的当前节点的左孩子或者右孩子是否可以加入路径,左边和右边有一个满足即可
return check(head.next, node.left) || check(head.next, node.right);
}
}