LeetCode Contest 178-1367. 二叉树中的列表 Linked List in Binary Tree
目录
一、中文版
给你一棵以 root 为根的二叉树和一个 head 为第一个节点的链表。
如果在二叉树中,存在一条一直向下的路径,且每个点的数值恰好一一对应以 head 为首的链表中每个节点的值,那么请你返回 True ,否则返回 False 。
一直向下的路径的意思是:从树中某个节点开始,一直连续向下的路径。
示例 1:
输入:head = [4,2,8], root = [1,4,4,null,2,2,null,1,null,6,8,null,null,null,null,1,3]
输出:true
解释:树中蓝色的节点构成了与链表对应的子路径。
示例 2:
输入:head = [1,4,2,6], root = [1,4,4,null,2,2,null,1,null,6,8,null,null,null,null,1,3]
输出:true
示例 3:
输入:head = [1,4,2,6,8], root = [1,4,4,null,2,2,null,1,null,6,8,null,null,null,null,1,3]
输出:false
解释:二叉树中不存在一一对应链表的路径。
提示:
二叉树和链表中的每个节点的值都满足 1 <= node.val <= 100 。
链表包含的节点数目在 1 到 100 之间。
二叉树包含的节点数目在 1 到 2500 之间。
二、英文版
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.
Example 2:
Input: head = [1,4,2,6], root = [1,4,4,null,2,2,null,1,null,6,8,null,null,null,null,1,3] Output: true Example 3: Input: head = [1,4,2,6,8], root = [1,4,4,null,2,2,null,1,null,6,8,null,null,null,null,1,3] Output: false Explanation: There is no path in the binary tree that contains all the elements of the linked list from head. Constraints: 1 <= node.val <= 100 for each node in the linked list and binary tree. The given linked list will contain between 1 and 100 nodes. The given binary tree will contain between 1 and 2500 nodes. 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/linked-list-in-binary-tree 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
三、My answer
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: # 比对是否存在和链表head相同的路径 def isSame(self, head: ListNode, root: TreeNode) -> bool: if not head: return True # 没有剩余链表节点返回真 if head and root and root.val == head.val: # 当前节点相同,比较左节点或右节点 return self.isSame(head.next, root.left) or self.isSame(head.next, root.right) return False # 当前节点不同,返回假 def isSubPath(self, head: ListNode, root: TreeNode) -> bool: if root: # 当前节点不为空 # 返回当前节点是否和链表一致,或者左子树是否含有链表路径,或者右子树是否含有链表路径 return self.isSame(head, root) or self.isSubPath(head, root.left) or self.isSubPath(head, root.right) return False
四、解题报告
题目给的节点数不多,可以直接比对二叉树中每一个节点的路径来判断是否和链表中的值一致。
isSubPath 和 isSame 都采用先根遍历即可。