101. Symmetric Tree
https://leetcode.com/problems/symmetric-tree/
Problem
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
For example, this binary tree [1,2,2,3,4,4,3]
is symmetric:
1
/ \
2 2
/ \ / \
3 4 4 3
But the following [1,2,2,null,3,null,3]
is not:
Follow up: Solve it both recursively and iteratively.
Solution
1. Recursive
/**
* 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) {
if (root == nullptr) return true;
return isSymmetric(root->left, root->right);
}
bool isSymmetric(TreeNode* left, TreeNode* right) {
if (left == nullptr) return right == nullptr;
if (right == nullptr) return left == nullptr;
return (left->val == right->val) && isSymmetric(left->left, right->right) && isSymmetric(left->right, right->left);
}
};
2. Iterative
/**
* 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) {
if (root == nullptr) return true;
return isSymmetric(root->left, root->right);
}
bool isSymmetric(TreeNode* left, TreeNode* right) {
if (left == nullptr) return right == nullptr;
if (right == nullptr) return left == nullptr;
queue<pair<TreeNode*, TreeNode*>> nodes;
nodes.push({left, right});
while (!nodes.empty()) {
auto pair = nodes.front(); nodes.pop();
if (pair.first == nullptr && pair.second == nullptr) continue;
if (pair.first == nullptr || pair.second == nullptr) return false;
if (pair.first->val != pair.second->val) return false;
nodes.push({pair.first->left, pair.second->right});
nodes.push({pair.first->right, pair.second->left});
}
return true;
}
};