剑指OFFER 树的子结构
题目描述
输入两棵二叉树A,B,判断B是不是A的子结构。(ps:我们约定空树不是任意一个树的子结构)
分析
先遍历A树,如果A树某个节点与B树的根节点相同,那么以这两个结点出发,看是否是是子结构.
判断子结构需要以这两个结点出发进行同步遍历
代码
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};*/
class Solution {
public:
TreeNode* tree1;
TreeNode* tree2;
bool res = false;
bool is_sub(TreeNode* node1, TreeNode* node2)
{
if (node2 == NULL)return true;
if (node1==NULL || node1->val!=node2->val)return false;
bool b_left = is_sub(node1->left, node2->left);
bool b_right = is_sub(node1->right, node2->right);
return b_left && b_right;
}
void recur(TreeNode* node)
{
if (node == NULL)return;
if (node->val == tree2->val) {
res = is_sub(node,tree2);
}
recur(node->left);
recur(node->right);
}
bool HasSubtree(TreeNode* pRoot1, TreeNode* pRoot2)
{
if (pRoot1 == NULL || pRoot2 == NULL)return false;
tree1 = pRoot1;
tree2 = pRoot2;
recur(tree1);
return res;
}
};