首页 > 其他 > 详细

Same Tree

时间:2015-06-18 19:13:18      阅读:152      评论:0      收藏:0      [点我收藏+]

Description:

Given two binary trees, write a function to check if they are equal or not.

Two binary trees are considered equal if they are structurally identical and the nodes have the same value.

Code:

    bool isSameTree(TreeNode *p, TreeNode *q) {
      deque<TreeNode*>mP;
      deque<TreeNode*>mQ;
      
      if (p==NULL && q==NULL)
        return true;
    
      if ((p==NULL || q==NULL))
        return false;
        
      mP.push_back(p);
      mQ.push_back(q);
      while (!mP.empty() && !mQ.empty())
      {
          TreeNode* temp_P = mP.front();
          TreeNode* temp_Q = mQ.front();
          
          mP.pop_front();
          mQ.pop_front();
            
          if ( (temp_P->val != temp_Q->val)
          || (temp_P->left == NULL || temp_Q->left == NULL) && (temp_P->left != temp_Q->left)
          || (temp_P->right == NULL || temp_Q->right == NULL) && (temp_P->right != temp_Q->right))
            return false;
            
          if (temp_P->left && temp_Q->left)
          {
            mP.push_back(temp_P->left);
            mQ.push_back(temp_Q->left);
          }
          if (temp_P->right && temp_Q->right)
          {
            mP.push_back(temp_P->right);
            mQ.push_back(temp_Q->right);
          }
   
      }
      if (mP.empty() && mQ.empty())
        return true;
      else
        return false;
    }

 

Same Tree

原文:http://www.cnblogs.com/happygirl-zjj/p/4586490.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!