树的子结构
我感觉我对C++的指针和数据结构掌握的还可以了,后面加速看算法和面向对象的语法
题目描述
输入两棵二叉树A,B,判断B是不是A的子结构。(ps:我们约定空树不是任意一个树的子结构)
https://www.nowcoder.com/practice/6e196c44c7004d15b1610b9afca8bd88?tpId=13&tqId=11170&tPage=1&rp=1&ru=%2Fta%2Fcoding-interviews&qru=%2Fta%2Fcoding-interviews%2Fquestion-ranking
这个题我写的蛮顺利的,果然先想递归的实现方案是正确的思路。比较开心的是为了测试样例,又写了一个生成树的方法,算是额外的练习吧。
我的C++实现
#include <iostream>
#include <stack>
#include <time.h>
#include <stdlib.h>
using namespace std;
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};
//判断树的子结构
bool Compare(TreeNode* pRoot1, TreeNode* pRoot2)
{
if (pRoot1 == nullptr && pRoot2 != nullptr)
return false;
if (pRoot2 == nullptr)
return true;
if (pRoot1->val == pRoot2->val && Compare(pRoot1->left, pRoot2->left) && Compare(pRoot1->right, pRoot2->right))
return true;
else
return Compare(pRoot1->left, pRoot2) || Compare(pRoot1->right, pRoot2);
}
//空树返回false
bool HasSubtree(TreeNode* pRoot1, TreeNode* pRoot2)
{
return (pRoot2 == nullptr) ? false : Compare(pRoot1, pRoot2);
}
//前序遍历
void PreOrder(TreeNode* tree)
{ if (tree != nullptr)
{
cout<<tree->val<<" ";
PreOrder(tree->left);
PreOrder(tree->right);
}
}
//创建一棵树
TreeNode* CreateTree(int* treeValue, int length)
{
TreeNode* treeHead = nullptr;
TreeNode* treePtr[length];
for(int i = 0; i < length; i++)
{
TreeNode* newNode = new TreeNode(treeValue[i]);
if(i == 0)
{
treeHead = newNode;
}
else if((i - 1) / 2 >= 0)
{
if(i % 2 == 1)
(treePtr[(i - 1) / 2])->left = newNode;
else
(treePtr[(i - 1) / 2])->right = newNode;
}
else
{
cout<<"error"<<endl;
}
treePtr[i] = newNode;
}
PreOrder(treeHead);
cout<<endl;
return treeHead;
}
int main()
{
int treeValue1[] = {8,8,7,9,2,3,3,3,3,4,7};
int length = sizeof(treeValue1)/sizeof(treeValue1[0]);
TreeNode* tree1 = CreateTree(treeValue1, length);
int treeValue2[] = {8,9,2};
length = sizeof(treeValue2)/sizeof(treeValue2[0]);
TreeNode* tree2 = CreateTree(treeValue2, length);
if(HasSubtree(tree1, tree2))
cout<<"true"<<endl;
else
cout<<"false"<<endl;
}
到底值不值得呢??种树+10