(本博客旨在个人总结回顾)
题目描述:
输入两棵二叉树A和B,判断B是不是A的子结构。二叉树结点的定义如下:
struct BinaryTreeNode
{
int m_nValue;
BinaryTreeNode* m_pLeft;
BinaryTreeNode* m_pRight;
};
解题思路:
理解题目要求:B结构中结点所存的值与A子结构所存值相同即B为A的子结构。
要判断B结构是否为A的子结构就需要遍历A的子结构,可使用递归来解决该问题。
完整代码:
#include "stdafx.h"
#include <iostream>
using namespace std;
struct BinaryTreeNode
{
int m_nValue;
BinaryTreeNode* m_pLeft;
BinaryTreeNode* m_pRight;
};
/*
* @name IsTreeAHasTreeB
* @brief 递归遍历B结点与A结点值是否相同
* @param [in] BinaryTreeNode * pTreeA
* @param [in] BinaryTreeNode * pTreeB
* @return bool
*/
bool IsTreeAHasTreeB(BinaryTreeNode* pTreeA, BinaryTreeNode* pTreeB)
{
if (NULL == pTreeB)
{
return true;
}
if (NULL == pTreeA)
{
return false;
}
if (pTreeA->m_nValue != pTreeB->m_nValue)
{
return false;
}
return IsTreeAHasTreeB(pTreeA->m_pLeft, pTreeB->m_pLeft) && IsTreeAHasTreeB(pTreeA->m_pRight, pTreeB->m_pRight);
}
/*
* @name HasSubTree
* @brief 递归遍历与B跟结点相同的A结点
* @param [in] BinaryTreeNode * pTreeA
* @param [in] BinaryTreeNode * pTreeB
* @return bool
*/
bool HasSubTree(BinaryTreeNode* pTreeA, BinaryTreeNode* pTreeB)
{
bool bResult = false;
if (pTreeA != NULL && pTreeB != NULL)
{
if (pTreeA->m_nValue == pTreeB->m_nValue)
{
bResult = IsTreeAHasTreeB(pTreeA, pTreeB);
}
if (!bResult)
{
bResult = HasSubTree(pTreeA->m_pLeft, pTreeB);
}
if (!bResult)
{
bResult = HasSubTree(pTreeA->m_pRight, pTreeB);
}
}
return bResult;
}
int _tmain(int argc, _TCHAR* argv[])
{
//测试例子
//
// A B
// 8 8
// / \ / \
// 8 7 9 2
// / \
// 9 2
// / \
// 4 7
//
//
BinaryTreeNode* pTreeA = new BinaryTreeNode();
pTreeA->m_nValue = 8;
pTreeA->m_pLeft = new BinaryTreeNode();
pTreeA->m_pLeft->m_nValue = 8;
pTreeA->m_pLeft->m_pLeft = new BinaryTreeNode();
pTreeA->m_pLeft->m_pLeft->m_nValue = 9;
pTreeA->m_pLeft->m_pRight = new BinaryTreeNode();
pTreeA->m_pLeft->m_pRight->m_nValue = 2;
pTreeA->m_pLeft->m_pRight->m_pLeft = new BinaryTreeNode();
pTreeA->m_pLeft->m_pRight->m_pLeft->m_nValue = 4;
pTreeA->m_pLeft->m_pRight->m_pRight = new BinaryTreeNode();
pTreeA->m_pLeft->m_pRight->m_pRight->m_nValue = 7;
pTreeA->m_pRight = new BinaryTreeNode();
pTreeA->m_pRight->m_nValue = 7;
BinaryTreeNode* pTreeB = new BinaryTreeNode();
pTreeB->m_nValue = 8;
pTreeB->m_pLeft = new BinaryTreeNode();
pTreeB->m_pLeft->m_nValue = 9;
pTreeB->m_pRight = new BinaryTreeNode();
pTreeB->m_pRight->m_nValue = 2;
cout << "pTreeA has pTreeB:" << (HasSubTree(pTreeA, pTreeB) == true ? "true" : "false") << endl;
cout << "pTreeA has pTreeB:" << (HasSubTree(pTreeA, NULL) == true ? "true" : "false") << endl;
cout << "pTreeA has pTreeB:" << (HasSubTree(NULL, pTreeB) == true ? "true" : "false") << endl;
cout << "pTreeA has pTreeB:" << (HasSubTree(NULL, NULL) == true ? "true" : "false") << endl;
system("pause");
return 0;
}
运行结果: