Skip to content
This repository was archived by the owner on Apr 27, 2025. It is now read-only.

Commit 20bbf4f

Browse files
committed
101. Symmetric Tree
1 parent ded94ed commit 20bbf4f

File tree

1 file changed

+64
-0
lines changed

1 file changed

+64
-0
lines changed

101. Symmetric Tree.md

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
# 101. Symmetric Tree
2+
3+
### 2017-03-31
4+
5+
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
6+
7+
For example, this binary tree `[1,2,2,3,4,4,3]` is symmetric:
8+
9+
```
10+
1
11+
/ \
12+
2 2
13+
/ \ / \
14+
3 4 4 3
15+
16+
```
17+
18+
But the following `[1,2,2,null,3,null,3]` is not:
19+
20+
```
21+
1
22+
/ \
23+
2 2
24+
\ \
25+
3 3
26+
27+
```
28+
29+
**Note:**
30+
Bonus points if you could solve it both recursively and iteratively.
31+
32+
33+
34+
# Solution
35+
36+
```swift
37+
/**
38+
* Definition for a binary tree node.
39+
* public class TreeNode {
40+
* public var val: Int
41+
* public var left: TreeNode?
42+
* public var right: TreeNode?
43+
* public init(_ val: Int) {
44+
* self.val = val
45+
* self.left = nil
46+
* self.right = nil
47+
* }
48+
* }
49+
*/
50+
class Solution {
51+
func isSymmetric(_ root: TreeNode?) -> Bool {
52+
func isSymmetric(left: TreeNode?, right: TreeNode?) -> Bool {
53+
guard let l = left, let r = right, l.val == r.val else {
54+
return (left == nil && right == nil)
55+
}
56+
return isSymmetric(left: l.left, right: r.right) && isSymmetric(left: l.right, right: r.left)
57+
}
58+
return isSymmetric(left: root?.left, right: root?.right)
59+
60+
}
61+
62+
}
63+
```
64+

0 commit comments

Comments
 (0)