Skip to content

Commit c42d269

Browse files
committed
improved 515 solution
1 parent 28567f3 commit c42d269

File tree

2 files changed

+57
-0
lines changed

2 files changed

+57
-0
lines changed

problems/problem0515/largest_node_level.go

+31
Original file line numberDiff line numberDiff line change
@@ -32,3 +32,34 @@ func largestValues(root *TreeNode) []int {
3232
}
3333
return res
3434
}
35+
36+
func largestValuesRec(root *TreeNode) []int {
37+
var res []int
38+
var solve func(*TreeNode, int)
39+
40+
if root == nil {
41+
return nil
42+
}
43+
44+
solve = func(tn *TreeNode, i int) {
45+
if i >= len(res) {
46+
res = append(res, tn.Val)
47+
} else {
48+
if res[i] < tn.Val {
49+
res[i] = tn.Val
50+
}
51+
}
52+
53+
if tn.Left != nil {
54+
solve(tn.Left, i+1)
55+
}
56+
57+
if tn.Right != nil {
58+
solve(tn.Right, i+1)
59+
}
60+
}
61+
62+
solve(root, 0)
63+
64+
return res
65+
}

problems/problem0515/largest_node_level_test.go

+26
Original file line numberDiff line numberDiff line change
@@ -27,3 +27,29 @@ func TestLargestNodeLevel(t *testing.T) {
2727
assert.Equal(want, got, fmt.Sprintf("%+v", res))
2828
}
2929
}
30+
31+
func BenchmarkLargestNodeLevel(b *testing.B) {
32+
for i := 0; i < b.N; i++ {
33+
for _, res := range Results {
34+
largestValues(res.Input)
35+
}
36+
}
37+
}
38+
39+
func TestLargestNodeLevelRec(t *testing.T) {
40+
assert := assert.New(t)
41+
42+
for _, res := range Results {
43+
want := res.Expected
44+
got := largestValuesRec(res.Input)
45+
assert.Equal(want, got, fmt.Sprintf("%+v", res))
46+
}
47+
}
48+
49+
func BenchmarkLargestNodeLevelRec(b *testing.B) {
50+
for i := 0; i < b.N; i++ {
51+
for _, res := range Results {
52+
largestValuesRec(res.Input)
53+
}
54+
}
55+
}

0 commit comments

Comments
 (0)