100.判断两个二叉树是否完全相等 Same Tree
递归实现
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;
}