Skip to content

Commit 0d9232b

Browse files
author
Shuo
authored
Merge pull request #382 from openset/develop
Add: Cousins in Binary Tree
2 parents b9d1adc + 9a5c65d commit 0d9232b

File tree

2 files changed

+95
-0
lines changed

2 files changed

+95
-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 && xd == 0 && yd == 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: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
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+
input: []int{1, 2, 3, NULL, 4, 5},
38+
x: 4,
39+
y: 5,
40+
expected: true,
41+
},
42+
{
43+
input: []int{1, 2, 3, NULL, 4, 5},
44+
x: 5,
45+
y: 4,
46+
expected: true,
47+
},
48+
}
49+
for _, tc := range tests {
50+
output := isCousins(SliceInt2TreeNode(tc.input), tc.x, tc.y)
51+
if output != tc.expected {
52+
t.Fatalf("input: %v, output: %v, expected: %v", tc.input, output, tc.expected)
53+
}
54+
}
55+
}

0 commit comments

Comments
 (0)