码迷,mamicode.com
首页 > 其他好文 > 详细

Same Tree

时间:2015-06-18 19:15:25      阅读:93      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!