Last active
August 6, 2020 13:56
-
-
Save betandr/53b921476b6596ffed5d363eec68479e to your computer and use it in GitHub Desktop.
Sum a tree using nil pointer receivers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import "fmt" | |
type node struct { | |
v int | |
l *node | |
r *node | |
} | |
func (n *node) sum() int { | |
if n == nil { | |
return 0 | |
} | |
return n.v + n.l.sum() + n.r.sum() | |
} | |
// n1 | |
// / \ | |
// n2 n3 | |
// / \ \ | |
// n4 n5 n6 | |
// / \ / | |
// n7 n8 n9 | |
func main() { | |
n7 := node{3, nil, nil} | |
n8 := node{5, nil, nil} | |
n4 := node{v: 1, l: nil, r: nil} | |
n5 := node{v: 4, l: &n7, r: &n8} | |
n2 := node{v: 2, l: &n4, r: &n5} | |
n9 := node{v: 8, l: nil, r: nil} | |
n6 := node{v: 9, l: &n9, r: nil} | |
n3 := node{v: 7, l: nil, r: &n6} | |
n1 := node{v: 6, l: &n2, r: &n3} | |
fmt.Println(n1.sum()) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment