leetcodeSolution to some Leetcode problems written in C++ |
git clone git://git.dimitrijedobrota.com/leetcode.git |
Log | Files | Refs | README | LICENSE |
0100.cpp (1009B)
0 // Recursive solution
1 class Solution {
2 public:
3 bool isSameTree(TreeNode *p, TreeNode *q) {
4 if (!p && !q) return true;
5 if (!p || !q) return false;
6 return p->val == q->val && isSameTree(p->left, q->left) && isSameTree(p->right, q->right);
7 }
8 };
10 // Iterative solution
11 class Solution {
12 public:
13 bool isSameTree(TreeNode *p, TreeNode *q) {
14 if (!p && !q) return true;
15 if (!p || !q) return false;
16 queue<pair<TreeNode *, TreeNode *>> qu;
17 qu.push({p, q});
18 while (!qu.empty()) {
19 auto [p, q] = qu.front();
20 qu.pop();
21 if (p->val != q->val) return false;
23 if (p->left && q->left)
24 qu.push({p->left, q->left});
25 else if (p->left || q->left)
26 return false;
28 if (p->right && q->right)
29 qu.push({p->right, q->right});
30 else if (p->right || q->right)
31 return false;
32 }
34 return true;
35 }
36 };