AcWing 37. 树的子结构
原题链接
简单
作者:
George
,
2020-11-18 23:24:03
,
所有人可见
,
阅读 443
/**
* 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* p, TreeNode* q) {
if(!p || !q) return false;
if(contain(p, q)) return true;
return hasSubtree(p->left, q) || hasSubtree(p->right, q);
}
bool contain(TreeNode* p, TreeNode* q){
if(!q) return true;
if(!p || p->val != q->val) return false;
return contain(p->left, q->left) && contain(p->right, q->right);
}
};