剑指offer-树的子结构

11.树的子结构

题目内容:

代码及思路:

如果有更好的写法,非常愿意和大家一起交流

#include<iostream>
using namespace std;
struct TreeNode
{
	int val;
	TreeNode* left;
	TreeNode* right;
};
class solution
{
	public:
		void buildtree(TreeNode** root)
		{
			int temp;
			cin >> temp;
			if (temp == 0)
			{
				(*root)->val = 0;
				(*root) = nullptr;
				return;
			}
			else
			{
				(*root)->val = temp;
				(*root)->left = new TreeNode;
				buildtree(&(*root)->left);
				(*root)->right = new TreeNode;
				buildtree(&(*root)->right);
			}
		}
		//输入的是两棵二叉树,因为约定空树不是任意一个树的子结构
		bool hassubtree(TreeNode* p1, TreeNode* p2)
		{
			//若任意一个树为空,输出都为false(此处p1位题目中的A,p2为题目中的B)
			bool res = false;
			if (p1 != nullptr&&p2 != nullptr)
			{
				//首先在A树中查找与B树根节点相同的节点位置,然后再遍历子树
				if (p1->val == p2->val)
					res = Doeshassubtree(p1, p2); //再遍历子树,若某个节点处不相同,则继续在左右子树中寻找
				if (!res)
					res = hassubtree(p1->left, p2);
				if (!res)
					res = hassubtree(p1->right, p2);
			}
			return res;
		}
		//
		bool Doeshassubtree(TreeNode* root1, TreeNode* root2)
		{
			if (root2 == nullptr)
				return true;
			if (root1 == nullptr)
				return false;
			if (root1->val != root2->val)
				return false;
			return Doeshassubtree(root1->left, root2->left) && Doeshassubtree(root1->right, root2->right);//分别依次比较左右子树
		}
};
void main()
{
	solution* object = new solution();
	TreeNode* p1 = new TreeNode;
	TreeNode* p2 = new TreeNode;
	object->buildtree(&p1);
	object->buildtree(&p2);
	bool res = object->hassubtree(p1, p2);
	cout << res << endl;
	
}

第一部分构造二叉树的部分,如果是如下的一棵树:

则输入为1 2 4 0 0 5 0 0 3 6 0 0 7 0 0

大家有没有更好的输入创建方式呀,好苦恼,感觉这样写很麻烦一点也不直接

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值