77// 题目:输入两棵二叉树A和B,判断B是不是A的子结构。
88
99#include < cstdio>
10- #include " ..\Utilities\BinaryTree.h"
10+
11+ struct BinaryTreeNode
12+ {
13+ double m_dbValue;
14+ BinaryTreeNode* m_pLeft;
15+ BinaryTreeNode* m_pRight;
16+ };
1117
1218bool DoesTree1HaveTree2 (BinaryTreeNode* pRoot1, BinaryTreeNode* pRoot2);
19+ bool Equal (double num1, double num2);
1320
1421bool HasSubtree (BinaryTreeNode* pRoot1, BinaryTreeNode* pRoot2)
1522{
1623 bool result = false ;
1724
1825 if (pRoot1 != nullptr && pRoot2 != nullptr )
1926 {
20- if (pRoot1->m_nValue == pRoot2->m_nValue )
27+ if (Equal ( pRoot1->m_dbValue , pRoot2->m_dbValue ) )
2128 result = DoesTree1HaveTree2 (pRoot1, pRoot2);
2229 if (!result)
2330 result = HasSubtree (pRoot1->m_pLeft , pRoot2);
@@ -36,13 +43,56 @@ bool DoesTree1HaveTree2(BinaryTreeNode* pRoot1, BinaryTreeNode* pRoot2)
3643 if (pRoot1 == nullptr )
3744 return false ;
3845
39- if (pRoot1->m_nValue != pRoot2->m_nValue )
46+ if (! Equal ( pRoot1->m_dbValue , pRoot2->m_dbValue ) )
4047 return false ;
4148
4249 return DoesTree1HaveTree2 (pRoot1->m_pLeft , pRoot2->m_pLeft ) &&
4350 DoesTree1HaveTree2 (pRoot1->m_pRight , pRoot2->m_pRight );
4451}
4552
53+ bool Equal (double num1, double num2)
54+ {
55+ if ((num1 - num2 > -0.0000001 ) && (num1 - num2 < 0.0000001 ))
56+ return true ;
57+ else
58+ return false ;
59+ }
60+
61+ // ====================辅助测试代码====================
62+ BinaryTreeNode* CreateBinaryTreeNode (double dbValue)
63+ {
64+ BinaryTreeNode* pNode = new BinaryTreeNode ();
65+ pNode->m_dbValue = dbValue;
66+ pNode->m_pLeft = nullptr ;
67+ pNode->m_pRight = nullptr ;
68+
69+ return pNode;
70+ }
71+
72+ void ConnectTreeNodes (BinaryTreeNode* pParent, BinaryTreeNode* pLeft, BinaryTreeNode* pRight)
73+ {
74+ if (pParent != nullptr )
75+ {
76+ pParent->m_pLeft = pLeft;
77+ pParent->m_pRight = pRight;
78+ }
79+ }
80+
81+ void DestroyTree (BinaryTreeNode* pRoot)
82+ {
83+ if (pRoot != nullptr )
84+ {
85+ BinaryTreeNode* pLeft = pRoot->m_pLeft ;
86+ BinaryTreeNode* pRight = pRoot->m_pRight ;
87+
88+ delete pRoot;
89+ pRoot = nullptr ;
90+
91+ DestroyTree (pLeft);
92+ DestroyTree (pRight);
93+ }
94+ }
95+
4696// ====================测试代码====================
4797void Test (char * testName, BinaryTreeNode* pRoot1, BinaryTreeNode* pRoot2, bool expected)
4898{
0 commit comments