检查子树。你有两棵非常大的二叉树:T1,有几万个节点;T2,有几万个节点。设计一个算法,判断 T2 是否为 T1 的子树。
如果 T1 有这么一个节点 n,其子树与 T2 一模一样,则 T2 为 T1 的子树,也就是说,从节点 n 处把树砍断,得到的树与 T2 完全相同。
题解:
/**
* 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 checkSubTree(TreeNode* t1, TreeNode* t2) {
if(t1==NULL&&t2==NULL) return true;//t1,t2为空,返回true
if(t1==NULL||t2==NULL) return false;//t1,t2其中只有一个为空,返回false
if(t1->val==t2->val){
return checkSubTree(t1->left,t2->left)&&checkSubTree(t1->right,t2->right);//结点相等,判断树是否相等
}else{
return checkSubTree(t1->left,t2)||checkSubTree(t1->right,t2);//不相等继续遍历左子树和右子树
}
}
};

被折叠的 条评论
为什么被折叠?



