遞歸實現
static public bool IsSameTree(TreeNode root1, TreeNode root2) {
if (root1 == null && root2 == null) {
return true;
}
if ((root1 == null && root2 != null) || (root1 != null && root2 == null)) {
return false;
}
if (root1.val != root2.val) {//判斷每個節點的值是否相等,如果去除此判斷,則判斷兩個二叉樹是否結構相等
return false;
}
return IsSameTree(root1.left, root2.left) && IsSameTree(root1.right, root2.right);
}
非遞歸實現方式
bool BTreeCompare(BTreeNode_t *pRoot1, BTreeNode_t *pRoot2)
{
if( pRoot1 == NULL && pRoot2 == NULL )
return false;
queue <BTreeNode_t *> que1;
queue <BTreeNode_t *> que2;
que1.push(pRoot1);
que2.push(pRoot2);
int curLevelNodeTotal1 = 0;
int curLevelNodeTotal2 = 0;
bool flag = true; //作為比較不一致時跳出標識
while( ( !que1.empty()) && ( !que2.empty())) //當兩個隊列均不為空時,才進行比較
{
curLevelNodeTotal1 = que1.size(); //獲取樹1的當前層節點總數
curLevelNodeTotal2 = que2.size(); //獲取樹2的當前層節點總數
if( curLevelNodeTotal1 != curLevelNodeTotal2){
flag = false;//當前層節點總數都不一致,不需要比較了,直接跳出
break;
}
int cnt1 = 0;//遍歷本層節點時的計數器
int cnt2 = 0;
while( cnt1 < curLevelNodeTotal1 && cnt2 < curLevelNodeTotal2){
++cnt1;
++cnt2;
pRoot1 = que1.front();
que1.pop();
pRoot2 = que2.front();
que2.pop();
//比較當前節點中數據是否一致
if( pRoot1->m_pElemt != pRoot2->m_pElemt ){
flag = false;
break;
}
//判斷pRoot1和pRoot2左右節點結構是否相同
if( ( pRoot1->m_pLeft != NULL && pRoot2->m_pLeft == NULL ) ||
( pRoot1->m_pLeft == NULL && pRoot2->m_pLeft != NULL ) ||
( pRoot1->m_pRight != NULL && pRoot2->m_pRight == NULL ) ||
( pRoot1->m_pRight == NULL && pRoot2->m_pRight != NULL )
){
flag = false;
break;
}
//將左右節點入隊
if( pRoot1->m_pLeft != NULL )
que1.push( pRoot1->m_pLeft);
if( pRoot1->m_pRight != NULL )
que1.push( pRoot1->m_pRight);
if( pRoot2->m_pLeft != NULL )
que2.push( pRoot2->m_pLeft);
if( pRoot2->m_pRight != NULL )
que2.push( pRoot2->m_pRight);
}
if( flag == false )
break;
}
//如果比較標志為false,則不相同
if( flag == false ){
while( !que1.empty() )
que1.pop();
while( !que2.empty())
que2.pop();
return false;
}
return true;
}