题目:输入两棵二叉树A和B,判断B是不是A的子结构。二叉树的结点定义如下:
struct BinaryTreeNode {
int m_nValue;
BinaryTreeNode* m_pLeftChild;
BinaryTreeNode* m_pRightChild;
};
思路:判断B是不是A的子树,先判断树B的根是否与A树的某子树的根结点是否一致,我们可以通过遍历二叉树数A的每一个结点,比较其是否与树B的根结点一样。如果找到满足添加的结点,我们分别比较其左右子树的根结点是否一致,可以利用递归重复上一步骤。
//有两棵二叉树A、B,判断B是否是A的子树
bool isSubTree(BinaryTreeNode* pRootA, BinaryTreeNode* pRootB) {
bool result = false;
if (NULL == pRootA || NULL == pRootB) {
return result;
}
//判断根结点是否一致
if (pRootA->m_nValue == pRootB->m_nValue) {
result = isAHasSubTreeB(pRootA, pRootB);
}
//如果根结点不一致,则比较与左子树的根是否一致
if (!result) {
result = isAHasSubTreeB(pRootA->m_pLeftChild, pRootB);
}
//如果左子树也不一致,则比较与右子树的根是否也一致
if (!result) {
result = isAHasSubTreeB(pRootA->m_pRightChild, pRootB);
}
return result;
}
//判断其子树是否满足条件
bool isAHasSubTreeB(BinaryTreeNode* pRootA, BinaryTreeNode* pRootB) {
//如果B树没有结点
if (NULL == pRootB) {
return true;
}
//如果B有结点而A没有对应的结点
if (NULL == pRootA) {
return false;
}
//判断根结点是否一致
if (pRootA->m_nValue != pRootB->m_nValue) {
return false;
}
//递归判断左右子树
return isAHasSubTreeB(pRootA->m_pLeftChild, pRootB->m_pLeftChild)
&& isAHasSubTreeB(pRootA->m_pRightChild, pRootB->m_pRightChild);
}
测试代码
/*
*
* Created on: 2014-3-23 15:13:11
* Author: danDingCongRong
*/
#include <stddef.h>
#include <iostream>
using namespace std;
int main() {
int n = 0;
cout << "输入测试数据的组数:" << endl;
cin >> n;
while (n) {
cout << "按先序序列创建二叉树:" << endl;
BinaryTreeNode* pABinaryTree = NULL;
pABinaryTree = createIntBinaryTree();
cout << "按先序序列创建二叉树:" << endl;
BinaryTreeNode* pBBinaryTree = NULL;
pBBinaryTree = createIntBinaryTree();
bool result = isSubTree(pABinaryTree, pBBinaryTree);
if (result) {
cout << "B是A的子结构。" << endl;
} else {
cout << "B不是A的子结构。" << endl;
}
--n;
}
return 0;
}
注:部分内容参考自剑指offer