-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathSymmetric_Tree.cpp
54 lines (48 loc) · 1.41 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
// http://oj.leetcode.com/submissions/detail/3903517
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
// recursively, Time Complexity: O(n), Space Complexity: O(logn)
class Solution {
public:
bool isSymmetric(TreeNode *root) {
return root ? isSymmetric(root->left, root->right) : true;
}
bool isSymmetric(TreeNode* left, TreeNode* right)
{
if (!left && !right) return true; // leaf
if (!left || !right) return false; // only has one branch
return left->val == right->val
&& isSymmetric(left->left, right->right)
&& isSymmetric(left->right, right->left);
}
};
// iteratively, Time Complexity: O(n), Space Complexity: O(logn)
class Solution {
public:
bool isSymmetric(TreeNode *root) {
if (!root) return true;
stack<TreeNode*> s;
s.push(root->left);
s.push(root->right);
while(!s.empty())
{
auto p = s.top(); s.pop();
auto q = s.top(); s.pop();
if (!p && !q) continue;
if (!p || !q) return false;
if (p->val != q->val) return false;
s.push(p->left);
s.push(q->right);
s.push(p->right);
s.push(q->left);
}
return true;
}
};