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 53af4bd

Browse files
committed
Add: Same Tree
1 parent 7177ee6 commit 53af4bd

File tree

2 files changed

+57
-0
lines changed

2 files changed

+57
-0
lines changed

‎problems/same-tree/same_tree.go

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,20 @@
11
package same_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 isSameTree(p *TreeNode, q *TreeNode) bool {
14+
if p == nil {
15+
return q == nil
16+
} else if q == nil || p.Val != q.Val {
17+
return false
18+
}
19+
return isSameTree(p.Left, q.Left) && isSameTree(p.Right, q.Right)
20+
}

‎problems/same-tree/same_tree_test.go

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,39 @@
11
package same_tree
2+
3+
import (
4+
"testing"
5+
6+
. "github.com/openset/leetcode/internal/kit"
7+
)
8+
9+
type caseType struct {
10+
p []int
11+
q []int
12+
expected bool
13+
}
14+
15+
func TestIsSameTree(t *testing.T) {
16+
tests := [...]caseType{
17+
{
18+
p: []int{1, 2, 3},
19+
q: []int{1, 2, 3},
20+
expected: true,
21+
},
22+
{
23+
p: []int{1, 2},
24+
q: []int{1, NULL, 2},
25+
expected: false,
26+
},
27+
{
28+
p: []int{1, 2, 1},
29+
q: []int{1, 1, 2},
30+
expected: false,
31+
},
32+
}
33+
for _, tc := range tests {
34+
output := isSameTree(SliceInt2TreeNode(tc.p), SliceInt2TreeNode(tc.q))
35+
if output != tc.expected {
36+
t.Fatalf("input: %v %v, output: %v, expected: %v", tc.p, tc.q, output, tc.expected)
37+
}
38+
}
39+
}

0 commit comments

Comments
(0)

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