LeetCode面试题 04.10. 检查子树

检查子树。你有两棵非常大的二叉树:T1,有几万个节点;T2,有几万个节点。设计一个算法,判断 T2 是否为 T1 的子树。

如果 T1 有这么一个节点 n,其子树与 T2 一模一样,则 T2 为 T1 的子树,也就是说,从节点 n 处把树砍断,得到的树与 T2 完全相同。

示例1:

输入:t1 = [1, 2, 3], t2 = [2]
输出:true
示例2:

输入:t1 = [1, null, 2, 4], t2 = [3, 2]
输出:false
提示:

树的节点数目范围为[0, 20000]。

#include <iostream>
using namespace std;

struct TreeNode {
	int val;
	TreeNode *left;
	TreeNode *right;
	TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};

bool checkSubTree(TreeNode* t1, TreeNode* t2) {
	if (!t1 && !t2)
		return true;
	if ((t1 && !t2) || (!t1 && t2))
		return false;
	if (t1->val == t2->val && checkSubTree(t1->left, t2->left) && checkSubTree(t1->right, t2->right))
		return true;
	else
		return checkSubTree(t1->left, t2) || checkSubTree(t1->right, t2);
}

int main() {
	TreeNode a1(1);
	TreeNode a2(1);
	TreeNode a3(2);
	a1.left = &a2;
	a2.right = &a3;
	TreeNode b1(1);
	TreeNode b2(2);
	b1.right = &b2;
	if (checkSubTree(&a1, &b1))
		cout << "true";
	else
		cout << "false";
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值