100.判断两个二叉树是否完全相等 Same Tree


递归实现
  1. static public bool IsSameTree(TreeNode root1, TreeNode root2) {
  2. if (root1 == null && root2 == null) {
  3. return true;
  4. }
  5. if ((root1 == null && root2 != null) || (root1 != null && root2 == null)) {
  6. return false;
  7. }
  8. if (root1.val != root2.val) {//判断每个节点的值是否相等,如果去除此判断,则判断两个二叉树是否结构相等
  9. return false;
  10. }
  11. return IsSameTree(root1.left, root2.left) && IsSameTree(root1.right, root2.right);
  12. }


非递归实现方式
  1. bool BTreeCompareBTreeNode_t *pRoot1, BTreeNode_t *pRoot2)
  2. {
  3. if( pRoot1 == NULL && pRoot2 == NULL )
  4. return false;
  5. queue <BTreeNode_t *> que1;
  6. queue <BTreeNode_t *> que2;
  7. que1.push(pRoot1);
  8. que2.push(pRoot2);
  9. int curLevelNodeTotal1 = 0;
  10. int curLevelNodeTotal2 = 0;
  11. bool flag = true; //作为比较不一致时跳出标识
  12. while( ( !que1.empty()) && ( !que2.empty())) //当两个队列均不为空时,才进行比较
  13. {
  14. curLevelNodeTotal1 = que1.size(); //获取树1的当前层节点总数
  15. curLevelNodeTotal2 = que2.size(); //获取树2的当前层节点总数
  16. if( curLevelNodeTotal1 != curLevelNodeTotal2){
  17. flag = false;//当前层节点总数都不一致,不需要比较了,直接跳出
  18. break;
  19. }
  20. int cnt1 = 0;//遍历本层节点时的计数器
  21. int cnt2 = 0;
  22. while( cnt1 < curLevelNodeTotal1 && cnt2 < curLevelNodeTotal2){
  23. ++cnt1;
  24. ++cnt2;
  25. pRoot1 = que1.front();
  26. que1.pop();
  27. pRoot2 = que2.front();
  28. que2.pop();
  29. //比较当前节点中数据是否一致
  30. if( pRoot1->m_pElemt != pRoot2->m_pElemt ){
  31. flag = false;
  32. break;
  33. }
  34. //判断pRoot1和pRoot2左右节点结构是否相同
  35. if( ( pRoot1->m_pLeft != NULL && pRoot2->m_pLeft == NULL ) ||
  36. ( pRoot1->m_pLeft == NULL && pRoot2->m_pLeft != NULL ) ||
  37. ( pRoot1->m_pRight != NULL && pRoot2->m_pRight == NULL ) ||
  38. ( pRoot1->m_pRight == NULL && pRoot2->m_pRight != NULL )
  39. ){
  40. flag = false;
  41. break;
  42. }
  43. //将左右节点入队
  44. if( pRoot1->m_pLeft != NULL )
  45. que1.push( pRoot1->m_pLeft);
  46. if( pRoot1->m_pRight != NULL )
  47. que1.push( pRoot1->m_pRight);
  48. if( pRoot2->m_pLeft != NULL )
  49. que2.push( pRoot2->m_pLeft);
  50. if( pRoot2->m_pRight != NULL )
  51. que2.push( pRoot2->m_pRight);
  52. }
  53. if( flag == false )
  54. break;
  55. }
  56. //如果比较标志为false,则不相同
  57. if( flag == false ){
  58. while( !que1.empty() )
  59. que1.pop();
  60. while( !que2.empty())
  61. que2.pop();
  62. return false;
  63. }
  64. return true;
  65. }





posted @ 2017-01-10 23:07  xiejunzhao  阅读(3007)  评论(0编辑  收藏  举报