Hello!
In this problem, a tree is input and you need to find the sum of all the branches in the tree. The algorithm for solving this problem is simple. Let’s take a tree
6
/ \
4 10
/ \ \
2 5 23
We start from the root, the sum here is 6. Go further down the tree in the left branch it will be 6 + 4 = 10 and in the right 10 + 6 = 16.
6 + 0
/ \
6 + 4 10 + 16
/ \ \
2 5 23
We move further on a tree in the left part it turns out 10 + 2 = 12 and 10 + 5 = 115 and in the right 16 + 23 = 39
6 + 0
/ \
6 + 4 10 + 6
/ \ \
10 + 2 5 + 10 23 + 16
We go further down the tree but there is no more data and therefore the sum we get 12, 15 and 39
package main
import (
"fmt"
)
type Tree struct {
root *Node
}
type Node struct {
key int
left *Node
right *Node
}
func main() {
tree := Tree{
&Node{
key: 5,
left: &Node{
key: 4,
},
right: &Node{
key: 10,
},
},
}
branchSum(tree)
}
func branchSum(tree Tree) {
sum := []int{}
branchSumHelper(tree.root, 0, &sum)
fmt.Println(sum)
}
func branchSumHelper(node *Node, runningSum int, sum *[]int) *[]int {
if node == nil {
return sum
}
newRunningSum := runningSum + node.key
if node.left == nil && node.right == nil {
*sum = append(*sum, newRunningSum)
return sum
}
branchSumHelper(node.left, newRunningSum, sum)
branchSumHelper(node.right, newRunningSum, sum)
return sum
}