Skip to main content

101. Symmetric Tree

Recursion

/*
* @lc app=leetcode id=101 lang=cpp
*
* [101] Symmetric Tree
*
* https://leetcode.com/problems/symmetric-tree/description/
*
* algorithms
* Easy (57.89%)
* Likes: 15947
* Dislikes: 410
* Total Accepted: 2.4M
* Total Submissions: 4M
* Testcase Example: '[1,2,2,3,4,4,3]'
*
* Given the root of a binary tree, check whether it is a mirror of itself
* (i.e., symmetric around its center).
*
*
* Example 1:
*
*
* Input: root = [1,2,2,3,4,4,3]
* Output: true
*
*
* Example 2:
*
*
* 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
*
*
*
* Follow up: Could you solve it both recursively and iteratively?
*/

// @lc code=start
/**
* 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);
}
};
// @lc code=end
  • T: O(N)O(N)
  • S: O(N)O(N)

iteration

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;
}
};
  • T: O(N)O(N)
  • S: O(N)O(N)