-
Notifications
You must be signed in to change notification settings - Fork 37
/
Copy path100. Same Tree.cpp
65 lines (61 loc) · 1.43 KB
/
100. Same Tree.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
// DFS
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool isSameTree(TreeNode* p, TreeNode* q) {
if (!p || !q) {
return !p && !q;
}
if (p->val != q->val) {
return false;
}
return isSameTree(p->left, q->left) && isSameTree(p->right, q->right);
}
};
// BFS
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool isSameTree(TreeNode* p, TreeNode* q) {
queue<TreeNode*>pq, qq;
pq.push(p);
qq.push(q);
while(!pq.empty() && !qq.empty()) {
auto a = pq.front();
pq.pop();
auto b = qq.front();
qq.pop();
if (!a || !b) {
if (!a && !b) {
continue;
} else {
return false;
}
}
if (a->val != b->val) {
return false;
}
pq.push(a->left);
pq.push(a->right);
qq.push(b->left);
qq.push(b->right);
}
return true;
}
};