AcWing 37. 树的子结构
原题链接
简单
作者:
adamXu
,
2020-09-26 13:53:48
,
所有人可见
,
阅读 467
/**
* 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 hasSubtree(TreeNode* pRoot1, TreeNode* pRoot2) {
//简单递归
if(!pRoot1 || !pRoot2) return false;
if(isPart(pRoot1,pRoot2)) return true;
return hasSubtree(pRoot1->left,pRoot2) || hasSubtree(pRoot1->right,pRoot2);
}
bool isPart(TreeNode* pRoot1, TreeNode* pRoot2){
if(!pRoot2) return true;
if(!pRoot1 || pRoot1->val != pRoot2->val) return false;
return isPart(pRoot1->left,pRoot2->left) && isPart(pRoot1->right,pRoot2->right);
}
};