题目描述
输入两棵二叉树A,B,判断B是不是A的子结构。(ps:我们约定空树不是任意一个树的子结构)
python:
# 首先判断A中是不是有B的根节点,如果没有,直接返回False
# 如果有,则判断A中的子树和B是否一样
class Solution:
def HasSubtree(self, pRoot1, pRoot2):
if pRoot1 is None or pRoot2 is None:
return False
else:
return self.isSame(pRoot1, pRoot2) or self.HasSubtree(pRoot1.left, pRoot2) or self.HasSubtree(pRoot1.right, pRoot2)
# 判断r2是不是r1的子结构,不是子树
def isSame(self, r1, r2):
if r2 is None:
return True
elif r1 is None:
return False
elif r1.val == r2.val:
return self.isSame(r1.left, r2.left) and self.isSame(r1.right, r2.right)
# r1.val与r2.val不相等
else:
return False
扩展:如果判断B是不是A的子树的话,python代码如下(HasSubtree函数同上):
# 判断r2是不是r1的子树
def isSame(self, r1, r2):
if r1 is None and r2 is None:
return True
# r1和r2有一个为None
elif r1 is None or r2 is None:
return False
elif r1.val == r2.val:
return self.isSame(r1.left, r2.left) and self.isSame(r1.right, r2.right)
# r1.val与r2.val不相等
else:
return False
c++:
#include<stdio.h>
using namespace std;
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};
class Solution {
public:
bool HasSubtree(TreeNode* pRoot1, TreeNode* pRoot2)
{
if(pRoot1 == NULL or pRoot2 == NULL){
return false;
}
else{
return IsSame(pRoot1, pRoot2) || HasSubtree(pRoot1->left, pRoot2) || HasSubtree(pRoot1->right, pRoot2);
}
}
bool IsSame(TreeNode *r1, TreeNode *r2){
if(r2 == NULL){
return true;
}
else if(r1 == NULL){
return false;
}
else if(r1->val == r2->val){
return IsSame(r1->left, r2->left) && IsSame(r1->right, r2->right);
}
else{
return false;
}
}
};