输入两棵二叉树 A,BA,B,判断 BB 是不是 AA 的子结构。
我们规定空树不是任何树的子结构。
数据范围
每棵树的节点数量 [0,1000][0,1000]。
样例
树 AA:
8
/ \
8 7
/ \
9 2
/ \
4 7
树 BB:
8
/ \
9 2
返回 true,因为 BB 是 AA 的子结构;
太简单了就不解释代码了
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool IsSon(TreeNode* r1, TreeNode* r2)
{
if(!r2)return true;
if(!r1&&!r2)return true;
if(!r1&&r2)return false;
if(!r1||r2->val!=r1->val)return false;
return IsSon(r1->left,r2->left)&&IsSon(r1->right,r2->right);
}
bool hasSubtree(TreeNode* pRoot1, TreeNode* pRoot2) {
if(!pRoot2||!pRoot1)
return false;
if(IsSon(pRoot1,pRoot2))
return true;
return hasSubtree(pRoot1->left,pRoot2)||hasSubtree(pRoot1->right,pRoot2);
}
};