class Solution {
public:
/**
* @param T1, T2: The roots of binary tree.
* @return: True if T2 is a subtree of T1, or false.
*/
bool isSubtree(TreeNode *T1, TreeNode *T2) {
if ( T2 == NULL )return true;
if ( T1 == NULL )return false;
bool result = false;
result = TreeCmp(T1, T2);
//将所有结果或起来就可以,因为只要有一个地方是子树,就为子树,但这样貌似会比较慢
return isSubtree(T1->left, T2) || isSubtree(T1->right, T2) || result;
}
//TreeCmp用来比较当前是否是当前节点开始的子树,这个函数很重要
bool TreeCmp (TreeNode *T1, TreeNode *T2) {
if (T1 != nullptr && T2!=nullptr && T1->val == T2->val) {
return TreeCmp(T1->left,T2->left) && TreeCmp (T1->right,T2->right);
}
if (T1 == nullptr && T2 == nullptr) {
return true;
}
return false;
}
};
LintCode-剑指Offer-(245)子树
最新推荐文章于 2015-12-05 14:25:16 发布