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 b51545e

Browse files
committed
Add: Cousins in Binary Tree
1 parent 85c91ec commit b51545e

File tree

2 files changed

+83
-0
lines changed

2 files changed

+83
-0
lines changed
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
package cousins_in_binary_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 isCousins(root *TreeNode, x int, y int) bool {
14+
xp, yp, xd, yd, depth := 0, 0, 0, 0, 0
15+
queue := []*TreeNode{root}
16+
for l := len(queue); l > 0; l = len(queue) {
17+
for _, node := range queue {
18+
if node.Left != nil {
19+
if node.Left.Val == x {
20+
xp, xd = node.Val, depth+1
21+
} else if node.Left.Val == y {
22+
yp, yd = node.Val, depth+1
23+
} else {
24+
queue = append(queue, node.Left)
25+
}
26+
}
27+
if node.Right != nil {
28+
if node.Right.Val == x {
29+
xp, xd = node.Val, depth+1
30+
} else if node.Right.Val == y {
31+
yp, yd = node.Val, depth+1
32+
} else {
33+
queue = append(queue, node.Right)
34+
}
35+
}
36+
}
37+
depth, queue = depth+1, queue[l:]
38+
}
39+
return xp != yp && xd == yd
40+
}
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
package cousins_in_binary_tree
2+
3+
import (
4+
"testing"
5+
6+
. "github.com/openset/leetcode/internal/kit"
7+
)
8+
9+
type caseType struct {
10+
input []int
11+
x int
12+
y int
13+
expected bool
14+
}
15+
16+
func TestIsCousins(t *testing.T) {
17+
tests := [...]caseType{
18+
{
19+
input: []int{1, 2, 3, 4},
20+
x: 4,
21+
y: 3,
22+
expected: false,
23+
},
24+
{
25+
input: []int{1, 2, 3, NULL, 4, NULL, 5},
26+
x: 5,
27+
y: 4,
28+
expected: true,
29+
},
30+
{
31+
input: []int{1, 2, 3, NULL, 4},
32+
x: 2,
33+
y: 3,
34+
expected: false,
35+
},
36+
}
37+
for _, tc := range tests {
38+
output := isCousins(SliceInt2TreeNode(tc.input), tc.x, tc.y)
39+
if output != tc.expected {
40+
t.Fatalf("input: %v, output: %v, expected: %v", tc.input, output, tc.expected)
41+
}
42+
}
43+
}

0 commit comments

Comments
(0)

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