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
大家有没有更好的输入创建方式呀,好苦恼,感觉这样写很麻烦一点也不直接