Given a binary tree root
and a linked list with head
as the first node.
Return True if all the elements in the linked list starting from the head
correspond to some downward path connected in the binary tree otherwise return False.
In this context downward path means a path that starts at some node and goes downwards.
Example 1:
Input: head = [4,2,8], root = [1,4,4,null,2,2,null,1,null,6,8,null,null,null,null,1,3]
Output: true
Explanation: Nodes in blue form a subpath in the binary Tree.
思路:这题跟572很相似,就是遇见了相同的点,就开始做dfs,判断是否连续一致,一致就return true,否则,就tree 遍历;
这种类型的题就是纯粹考察recursion,一般2层recursion,最外层控制方向,内层判断
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
// 注意跟572 subtree of Another tree, 不一样的地方是:listnode有可能走完了变成null,但是tree还没走完;
// 所以base case的判断条件,跟572是有点区别的;
public boolean isSubPath(ListNode head, TreeNode root) {
if(head == null) {
return true;
}
if(root == null) {
return false;
}
if(head.val == root.val && issame(head, root)) {
return true;
}
return isSubPath(head, root.left) || isSubPath(head, root.right);
}
public boolean issame(ListNode head, TreeNode root) {
if(head == null) {
return true;
}
if(root == null) {
return false;
}
if(head.val != root.val) {
return false;
}
return issame(head.next, root.left) || issame(head.next, root.right);
}
}