LintCode 子树
有两个不同大小的二进制树: T1
有上百万的节点; T2
有好几百的节点。请设计一种算法,判定 T2
是否为 T1
的子树。
样例
下面的例子中 T2 是 T1 的子树:
1 3
/ \ /
T1 = 2 3 T2 = 4
/
4
下面的例子中 T2 不是 T1 的子树:
1 3 / \ \ T1 = 2 3 T2 = 4 / 4
分析:醉了!!!
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
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) {
// write your code here
bool result=false;
if(T2 == nullptr)
return true;
if(T1 == nullptr)
return false;
if(T1->val == T2->val)
{
result=DoesTree1HaveTree2(T1,T2);
}
if(!result)
{
result=isSubtree(T1->left,T2);
}
if(!result)
{
result=isSubtree(T1->right,T2);
}
return result;
}
bool DoesTree1HaveTree2(TreeNode *T1, TreeNode *T2)
{
if (T1!=nullptr && T2!=nullptr && T1->val == T2->val)
return DoesTree1HaveTree2(T1->left,T2->left) && DoesTree1HaveTree2(T1->right,T2->right);//刚开始一直错误 原来是这块的问题 必须要写T1不为NULL和T2不为NULL
if (T1 == nullptr && T2 == nullptr)
{
return true;
}
return false;
}
};