101. 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:
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
From: LeetCode
Link: 101. Symmetric Tree
Solution:
Ideas:
- Check if the root is null. If it’s null, then the tree is symmetric.
- Otherwise, check if the left subtree of the root is a mirror image of the right subtree.
To check if two trees are mirror images of each other:
- If both trees are null, return true.
- If one tree is null and the other isn’t, return false.
- If the values of the root nodes of the two trees are not the same, return false.
- Recursively check if the left subtree of the first tree is a mirror image of the right subtree of the second tree and vice versa.
Code:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
bool isMirror(struct TreeNode* t1, struct TreeNode* t2) {
if (t1 == NULL && t2 == NULL) return true;
if (t1 == NULL || t2 == NULL) return false;
return (t1->val == t2->val)
&& isMirror(t1->right, t2->left)
&& isMirror(t1->left, t2->right);
}
bool isSymmetric(struct TreeNode* root) {
return isMirror(root, root);
}