原文链接: https://leetcode-cn.com/problems/linked-list-in-binary-tree
英文原文
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:
- The number of nodes in the tree will be in the range
[1, 2500]
. - The number of nodes in the list will be in the range
[1, 100]
. 1 <= Node.val <= 100
for each node in the linked list and 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
之间。
通过代码
高赞题解
相关题目
代码
周赛题,如果做过上面的就很容易啦,加点注释~~
class Solution {
public boolean isSubPath(ListNode head, TreeNode root) {
if (head == null) {
return true;
}
if (root == null) {
return false;
}
//先判断当前的节点,如果不对,再看左子树和右子树呗
return isSub(head, root) || isSubPath(head, root.left) || isSubPath(head, root.right);
}
private boolean isSub(ListNode head, TreeNode node) {
//特判:链表走完了,返回true
if (head == null) {
return true;
}
//特判:链表没走完,树走完了,这肯定不行,返回false
if (node == null) {
return false;
}
//如果值不同,必定不是啊
if (head.val != node.val) {
return false;
}
//如果值相同,继续看,左边和右边有一个满足即可
return isSub(head.next, node.left) || isSub(head.next, node.right);
}
}
class Solution {
public:
bool isSubPath(ListNode* head, TreeNode* root) {
if(head == nullptr) return true;
if(root == nullptr) return false;
return dfs(head,root) || isSubPath(head,root->left) || isSubPath(head,root->right);
}
bool dfs(ListNode *head,TreeNode *node){
if(head == nullptr) return true;
if(node == nullptr) return false;
if(head->val != node->val) return false;
return dfs(head->next,node->left) || dfs(head-> next,node->right);
}
};
统计信息
通过次数 | 提交次数 | AC比率 |
---|---|---|
15720 | 37548 | 41.9% |
提交历史
提交时间 | 提交结果 | 执行时间 | 内存消耗 | 语言 |
---|