0%

symmetric-tree

Symmetric Tree – LeetCode 101

Problem

Description

Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).

Answer

Original

Code

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
/**
* 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 issymmetric(TreeNode* p, TreeNode* q){
if(p != nullptr && q != nullptr){
if(p->val == q->val)
return issymmetric(p->right,q->left) && issymmetric(p->left,q->right);
else
return false;
} else if (p == nullptr && q == nullptr) return true;
else {return false;}
}

bool isSymmetric(TreeNode* root) {
if(!root) return true;
return issymmetric(root->left,root->right);
}
};

思路

复用上题的代码,把一棵树交换左右节点分解成两颗树即可。时间复杂度$O(n)$,$n$为节点数,空间复杂度$O(n)$。
耗时$6$ ms,排名$96.44\%$

Better

思路

同样使用DFS的迭代来实现,时间复杂度$O(n)$,$n$为节点数,空间复杂度$O(n)$。也可以看LeetCode官方解
耗时$6$ ms,排名$96.44\%$

Code

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
/**
* 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 isSymmetric(TreeNode* root) {
queue<TreeNode *> q;
q.push(root);
q.push(root);
while(!q.empty()){
TreeNode *t1 = q.front(); q.pop();
TreeNode *t2 = q.front(); q.pop();
if(!t1 && !t2) continue;
if(!t1 || !t2) return false;
if(t1->val != t2->val) return false;
q.push(t1->left);
q.push(t2->right);
q.push(t1->right);
q.push(t2->left);
}
return true;
}
};