Same Tree

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;
    }

 

posted @ 2015-06-18 17:22  Rosanne  阅读(146)  评论(0编辑  收藏  举报