leetcode

Solution to some Leetcode problems written in C++
git clone git://git.dimitrijedobrota.com/leetcode.git
Log | Files | Refs | README | LICENSE

0100.cpp (1009B)


      1 // Recursive solution
      2 class Solution {
      3   public:
      4     bool isSameTree(TreeNode *p, TreeNode *q) {
      5         if (!p && !q) return true;
      6         if (!p || !q) return false;
      7         return p->val == q->val && isSameTree(p->left, q->left) && isSameTree(p->right, q->right);
      8     }
      9 };
     10 
     11 // Iterative solution
     12 class Solution {
     13   public:
     14     bool isSameTree(TreeNode *p, TreeNode *q) {
     15         if (!p && !q) return true;
     16         if (!p || !q) return false;
     17         queue<pair<TreeNode *, TreeNode *>> qu;
     18         qu.push({p, q});
     19         while (!qu.empty()) {
     20             auto [p, q] = qu.front();
     21             qu.pop();
     22             if (p->val != q->val) return false;
     23 
     24             if (p->left && q->left)
     25                 qu.push({p->left, q->left});
     26             else if (p->left || q->left)
     27                 return false;
     28 
     29             if (p->right && q->right)
     30                 qu.push({p->right, q->right});
     31             else if (p->right || q->right)
     32                 return false;
     33         }
     34 
     35         return true;
     36     }
     37 };