-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path101. Symmetric Tree.cc
38 lines (32 loc) · 978 Bytes
/
101. Symmetric Tree.cc
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
//Using recursion method
//TC: O(n/2) = O(n)
//SC: O(logn)
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
bool Symmetric(TreeNode* p, TreeNode* q) {
if (p == nullptr && q == nullptr) {
return true;
} else if (p == nullptr || q == nullptr) {
return false;
} else if (p->val != q->val) {
return false;
}
return Symmetric(p->left, q->right) && Symmetric(p->right, q->left);
}
bool isSymmetric(TreeNode* root) {
if (root == nullptr)
return true;
return Symmetric(root->left, root->right);
}
};