Skip to content

Commit df17958

Browse files
committed
101. Symmetric Tree
1 parent 18d02eb commit df17958

File tree

3 files changed

+93
-0
lines changed

3 files changed

+93
-0
lines changed

symmetric-tree/Readme.md

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
# Problem: 101. Symmetric Tree
2+
3+
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
4+
5+
For example, this binary tree [1,2,2,3,4,4,3] is symmetric:
6+
7+
```go
8+
1
9+
/ \
10+
2 2
11+
/ \ / \
12+
3 4 4 3
13+
```
14+
15+
But the following [1,2,2,null,3,null,3] is not:
16+
17+
```go
18+
1
19+
/ \
20+
2 2
21+
\ \
22+
3 3
23+
```

symmetric-tree/main.go

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
package symmetrictree
2+
3+
// TreeNode data structure
4+
type TreeNode struct {
5+
Val int
6+
Left *TreeNode
7+
Right *TreeNode
8+
}
9+
10+
// Explanation: https://leetcode.com/articles/symmetric-tree/
11+
func isSymmetric(root *TreeNode) bool {
12+
return isMirror(root, root)
13+
}
14+
15+
func isMirror(left *TreeNode, right *TreeNode) bool {
16+
if left == nil && right == nil {
17+
return true
18+
}
19+
if left == nil || right == nil {
20+
return false
21+
}
22+
ret := left.Val == right.Val &&
23+
isMirror(left.Right, right.Left) &&
24+
isMirror(left.Left, right.Right)
25+
return ret
26+
}

symmetric-tree/main_test.go

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
package symmetrictree
2+
3+
import (
4+
"testing"
5+
)
6+
7+
func TestMaxDepth(t *testing.T) {
8+
testCases := []struct {
9+
Input *TreeNode
10+
Output bool
11+
}{
12+
{
13+
Input: &TreeNode{
14+
Val: 1,
15+
Left: &TreeNode{
16+
Val: 2,
17+
Left: &TreeNode{
18+
Val: 3,
19+
},
20+
Right: &TreeNode{
21+
Val: 4,
22+
},
23+
},
24+
Right: &TreeNode{
25+
Val: 2,
26+
Left: &TreeNode{
27+
Val: 4,
28+
},
29+
Right: &TreeNode{
30+
Val: 3,
31+
},
32+
},
33+
},
34+
Output: true,
35+
},
36+
}
37+
38+
for _, test := range testCases {
39+
out := isSymmetric(test.Input)
40+
if !(test.Output == out) {
41+
t.Errorf("expected to get %#v, but got %#v", test.Output, out)
42+
}
43+
}
44+
}

0 commit comments

Comments
 (0)