题目:
输入两颗二叉树A和B,判断B是不是A的子结构,二叉树结点的定义如下:
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};
判断B是不是A的子结构,得先找到A中和B中有相同val的根结点,然后在进一步判断两者是否有相同结构,有关二叉树的问题,用递归来解决比较方便。
class Solution {
public:
bool SameStructTree(TreeNode* pRoot1,TreeNode* pRoot2)
{
if (pRoot2 == NULL)
return true;
if (pRoot1 == NULL)
return false;
if (pRoot1->val != pRoot2->val)
return false;
return SameStructTree(pRoot1->left,pRoot2->left) && SameStructTree(pRoot1->right,pRoot2->right);
}
bool HasSubtree(TreeNode* pRoot1, TreeNode* pRoot2)
{
bool result = false;
if (pRoot1 != NULL && pRoot2 != NULL)
{
if (pRoot1->val == pRoot2->val)
result = SameStructTree(pRoot1,pRoot2);
if (!result)
result = SameStructTree(pRoot1->left,pRoot2);
if (!result)
result = SameStructTree(pRoot1->right,pRoot2);
}
return result;
}
};