## [101\. Symmetric Tree](https://leetcode.com/problems/symmetric-tree/) Given the `root` of a binary tree, _check whether it is a mirror of itself_ (i.e., symmetric around its center). **Example 1:** ![](https://assets.leetcode.com/uploads/2021/02/19/symtree1.jpg) **Input:** root = \[1,2,2,3,4,4,3\] **Output:** true **Example 2:** ![](https://assets.leetcode.com/uploads/2021/02/19/symtree2.jpg) **Input:** root = \[1,2,2,null,3,null,3\] **Output:** false **Constraints:** - The number of nodes in the tree is in the range `[1, 1000]`. - `-100 <= Node.val <= 100` 解法一:recursion ```cpp= /** * 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) { return isSame(root, root); } bool isSame(TreeNode* t1, TreeNode* t2) { if (!t1 && !t2) return true; if (!t1 || !t2) return false; if (t1->val != t2->val) return false; return isSame(t1->left, t2->right) && isSame(t1->right, t2->left); } }; ``` :::success - 時間複雜度:$O(N)$ - 空間複雜度:$O(N)$ ::: 解法二:iteration,用一個 queue,或兩個 queue ```cpp= /** * 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) { 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; } }; ``` :::success - 時間複雜度:$O(N)$ - 空間複雜度:$O(N)$ :::