Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 92297ae

Browse files
author
Shuo
authored
Merge pull request #420 from openset/develop
Add: Symmetric Tree
2 parents afc46ee + bcf535d commit 92297ae

File tree

2 files changed

+53
-0
lines changed

2 files changed

+53
-0
lines changed
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,24 @@
11
package symmetric_tree
2+
3+
import . "github.com/openset/leetcode/internal/kit"
4+
5+
/**
6+
* Definition for a binary tree node.
7+
* type TreeNode struct {
8+
* Val int
9+
* Left *TreeNode
10+
* Right *TreeNode
11+
* }
12+
*/
13+
func isSymmetric(root *TreeNode) bool {
14+
return isMirror(root, root)
15+
}
16+
17+
func isMirror(t1, t2 *TreeNode) bool {
18+
if t1 == nil && t2 == nil {
19+
return true
20+
} else if t1 == nil || t2 == nil {
21+
return false
22+
}
23+
return t1.Val == t2.Val && isMirror(t1.Left, t2.Right) && isMirror(t1.Right, t2.Left)
24+
}
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,31 @@
11
package symmetric_tree
2+
3+
import (
4+
"testing"
5+
6+
. "github.com/openset/leetcode/internal/kit"
7+
)
8+
9+
type caseType struct {
10+
input []int
11+
expected bool
12+
}
13+
14+
func TestIsSymmetric(t *testing.T) {
15+
tests := [...]caseType{
16+
{
17+
input: []int{1, 2, 2, 3, 4, 4, 3},
18+
expected: true,
19+
},
20+
{
21+
input: []int{1, 2, 2, NULL, 3, NULL, 3},
22+
expected: false,
23+
},
24+
}
25+
for _, tc := range tests {
26+
output := isSymmetric(SliceInt2TreeNode(tc.input))
27+
if output != tc.expected {
28+
t.Fatalf("input: %v, output: %v, expected: %v", tc.input, output, tc.expected)
29+
}
30+
}
31+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /