输入两个二叉树A,B,设计一个程序检测B是否是A的子树。
#include <iostream>
using namespace std;
struct BiTreeNode{
int val;
BiTreeNode* leftChild;
BiTreeNode* rightChild;
};
bool subTreeCheck(BiTreeNode* Root1, BiTreeNode* Root2){
if (Root2 == NULL)
return true;
if (Root1 == NULL)
return false;
if (Root1->val != Root2->val)
return false;
return subTreeCheck(Root1->leftChild, Root2->leftChild)
&& (Root1->rightChild, Root2->rightChild);
}
bool hasSubTree(BiTreeNode* Root1, BiTreeNode* Root2){
if (Root1 == NULL || Root2 == NULL) return false;
bool result = false;
if (Root1->val == Root2->val){
result = subTreeCheck(Root1, Root2);
}
if (!result) result = hasSubTree(Root1->leftChild, Root2);
if (!result) result = hasSubTree(Root1->rightChild, Root2);
return result;
}