5346. 二叉树中的列表(Leetcode178周赛)

5346. 二叉树中的列表

难度中等0

给你一棵以 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
解释:树中蓝色的节点构成了与链表对应的子路径。

提示:

二叉树和链表中的每个节点的值都满足 1 <= node.val <= 100 。
链表包含的节点数目在 1 到 100 之间。
二叉树包含的节点数目在 1 到 2500 之间。


class Solution {
public:
	int Save[101] = { 0 };
	int count = 0, save = 0;
	bool finish = 0;

	int judge(int num)
	{
		bool flag = 0;
		for (int i = 1; i < num; ++i)
		{
			for (int j = 0; j < num - i; j++)
			{
				if (Save[j] != Save[j + i])
					break;
				if (j == num - i - 1)
					return num - i;
			}
		}
		return 0;
	}
	void Pre_Find(TreeNode *t, int save)
	{
		//注意跳出条件
		if (t != NULL && finish == 0)
		{
			if (save == 0)
			{
				if (t->val == Save[0])
					save = 1;
			}
			else {
				if (t->val == Save[save])
				{
					save++;
				}
				else {
					save = judge(save);
					while (save > 0) {
						if (t->val == Save[save]) {
							save++;
							break;
						}
						else {
							save = judge(save);
						}
					}
					if (save == 0)
					{
						if (t->val == Save[save])
							save = 1;
					}
				}
			}
			if (save == count) {
				finish = 1;
				return;
			}
			Pre_Find(t->left, save);

			Pre_Find(t->right, save);
		}
	}
	bool isSubPath(ListNode* head, TreeNode* root) {
		if (head == NULL)
			return 1;
		if (root == NULL)
			return 0;

		ListNode* now = head;
		while (now != NULL)
		{
			Save[count++] = now->val;
			now = now->next;
		}

		Pre_Find(root, 0);
		return finish;

	}
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值