# Leetcode [No. 101] Symmetric Tree (EASY)
+ First Solved on 2023/12/29
+ second solved on 2025/01/04
## 題目
https://leetcode.com/problems/symmetric-tree/
## 思路
+ 這個解法其實不太算是我想的,但我覺得這個寫法很讚
+ 最主要就是在dfs裡面去判斷兩個node是否相同,如果相同的話就繼續往下比....
+ 跟一般的DFS差在他用兩個ptr去指
```c++=
/**
* 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 isSymmetric(TreeNode* root) {
// compare left to right
return isSameTree(root->left, root->right);
}
bool isSameTree(TreeNode* p, TreeNode* q)
{
if(p==q)
{
return true;
}
else if (p==nullptr && q!= nullptr || p != nullptr && q == nullptr)
{
return false;
}
else
{
return (p->val == q->val) && isSameTree(p->left, q->right) && isSameTree(p->right, q->left);
}
}
};
```
### 解法分析
+ time complexity: O(lgn)
### 執行結果

# 二次挑戰
## Intution
+ 根據代碼啟示錄的教學,再進行二度改良。
```c++=
class Solution {
public:
bool isSymmetric(TreeNode* root) {
return compare(root->left, root->right);
}
bool compare(TreeNode*left, TreeNode* right)
{
if(left == right) {
return true;
} else if (left && right) {
return left->val == right->val && compare(left->right, right->left) && compare(left->left, right->right);
} else {
return false;
}
}
};
```
## Analyze
+ Time complexity: O(n)
## Performance

## follow up:
> Follow up: Could you solve it both recursively and iteratively?
```C++=
```
### 解法分析
+ time complexity: O(nlgn)
### 執行結果