107 lines
2.2 KiB
Markdown
107 lines
2.2 KiB
Markdown
|
# Leetcode Symmetric-Tree
|
||
|
|
||
|
#### 2022-07-05 10:15
|
||
|
|
||
|
> ##### Algorithms:
|
||
|
> #algorithm #DFS #recursion
|
||
|
> ##### Data structures:
|
||
|
> #DS #binary_tree
|
||
|
> ##### Difficulty:
|
||
|
> #coding_problem #difficulty-easy
|
||
|
> ##### Additional tags:
|
||
|
> #leetcode
|
||
|
> ##### Revisions:
|
||
|
> N/A
|
||
|
|
||
|
##### Related topics:
|
||
|
```expander
|
||
|
tag:#DFS
|
||
|
```
|
||
|
|
||
|
|
||
|
|
||
|
##### Links:
|
||
|
- [Link to problem](https://leetcode.com/problems/symmetric-tree/)
|
||
|
___
|
||
|
### Problem
|
||
|
Given the `root` of a binary tree, _check whether it is a mirror of itself_ (i.e., symmetric around its center).
|
||
|
|
||
|
#### Examples
|
||
|
**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
|
||
|
**Constraints:**
|
||
|
|
||
|
- The number of nodes in the tree is in the range `[1, 1000]`.
|
||
|
- `-100 <= Node.val <= 100`
|
||
|
### Thoughts
|
||
|
|
||
|
> [!summary]
|
||
|
> This is a #DFS #recursion problem
|
||
|
|
||
|
Method 1, Recursion:
|
||
|
- Base Cases:
|
||
|
- left and right are nullptr: true
|
||
|
- else if left or right is nullptr: false, must be asymmetric
|
||
|
- left->val != right->val: false
|
||
|
- return check(left->left, right->right) && check(left->right, right->left)
|
||
|
|
||
|
|
||
|
### Solution
|
||
|
|
||
|
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 {
|
||
|
bool checkSymmetric(TreeNode *left, TreeNode *right) {
|
||
|
// If only one child is leaf it is not symmetric
|
||
|
if (!left && !right) {
|
||
|
return true;
|
||
|
} else if (!left || !right) {
|
||
|
return false;
|
||
|
}
|
||
|
|
||
|
if (left->val != right->val) {
|
||
|
return false;
|
||
|
}
|
||
|
|
||
|
// One node has two childs, traverse them in pairs.
|
||
|
return checkSymmetric(left->right, right->left) &&
|
||
|
checkSymmetric(left->left, right->right);
|
||
|
}
|
||
|
|
||
|
public:
|
||
|
bool isSymmetric(TreeNode *root) {
|
||
|
// DFS-like recursion
|
||
|
return checkSymmetric(root->left, root->right);
|
||
|
}
|
||
|
};
|
||
|
```
|
||
|
|
||
|
Iteration
|
||
|
```cpp
|
||
|
|
||
|
```
|