forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 1
/
symmetric-tree.cpp
70 lines (63 loc) · 1.75 KB
/
symmetric-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
66
67
68
69
70
// Time: O(n)
// Space: O(h), h is the height of the binary tree.
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
// Iterative solution.
class Solution {
public:
bool isSymmetric(TreeNode* root) {
if (!root) {
return true;
}
// isSymmetricHelper(root->left, root->right)
stack<TreeNode *> nodes;
nodes.emplace(root->left);
nodes.emplace(root->right);
while (!nodes.empty()) {
auto right = nodes.top();
nodes.pop();
auto left = nodes.top();
nodes.pop();
if (!left && !right) {
continue;
}
if (!left || !right || left->val != right->val) {
return false;
}
// isSymmetricHelper(left->right, right->left)
nodes.emplace(left->right);
nodes.emplace(right->left);
// isSymmetricHelper(left->left, right->right)
nodes.emplace(left->left);
nodes.emplace(right->right);
}
return true;
}
};
// Recursive solution.
class Solution2 {
public:
bool isSymmetric(TreeNode* root) {
if (!root) {
return true;
}
return isSymmetricHelper(root->left, root->right);
}
bool isSymmetricHelper(TreeNode *left, TreeNode *right) {
if (!left && !right) {
return true;
}
if (!left || !right || left->val != right->val) {
return false;
}
return isSymmetricHelper(left->left, right->right) &&
isSymmetricHelper(left->right, right->left);
}
};