Skip to content

Commit de18ebe

Browse files
author
Shuo
authored
Merge pull request #475 from openset/develop
Add: Sum of Root To Leaf Binary Numbers
2 parents 48c8d1c + f07a053 commit de18ebe

File tree

2 files changed

+62
-0
lines changed

2 files changed

+62
-0
lines changed
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
package sum_of_root_to_leaf_binary_numbers
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 sumRootToLeaf(root *TreeNode) int {
14+
if root.Left == nil && root.Right == nil {
15+
return root.Val
16+
}
17+
sum := 0
18+
if root.Left != nil {
19+
root.Left.Val += root.Val << 1
20+
sum += sumRootToLeaf(root.Left)
21+
}
22+
if root.Right != nil {
23+
root.Right.Val += root.Val << 1
24+
sum += sumRootToLeaf(root.Right)
25+
}
26+
return sum
27+
}
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
package sum_of_root_to_leaf_binary_numbers
2+
3+
import (
4+
"testing"
5+
6+
. "github.com/openset/leetcode/internal/kit"
7+
)
8+
9+
type caseType struct {
10+
input []int
11+
expected int
12+
}
13+
14+
func TestSumRootToLeaf(t *testing.T) {
15+
tests := [...]caseType{
16+
{
17+
input: []int{1, 0, 1, 0, 1, 0, 1},
18+
expected: 22,
19+
},
20+
{
21+
input: []int{1, 1},
22+
expected: 3,
23+
},
24+
{
25+
input: []int{1, NULL, 0},
26+
expected: 2,
27+
},
28+
}
29+
for _, tc := range tests {
30+
output := sumRootToLeaf(SliceInt2TreeNode(tc.input))
31+
if output != tc.expected {
32+
t.Fatalf("input: %v, output: %v, expected: %v", tc.input, output, tc.expected)
33+
}
34+
}
35+
}

0 commit comments

Comments
 (0)