User Tools

Site Tools


snippets:golang:containers:binarytree

**This is an old revision of the document!**

binary tree example

snippet.go
package main
 
import "fmt"
 
type TreeItem struct {
	Name string
	Age  int
 
	left  *TreeItem
	right *TreeItem
}
 
func (item *TreeItem) countChildren() int {
	count := 0
	if item.left != nil {
		count += item.left.countChildren() + 1
	}
	if item.right != nil {
		count += item.right.countChildren() + 1
	}
 
	return count
}
 
type Tree struct {
	root *TreeItem
}
 
func (tree *Tree) count() int {
	if tree.root == nil {
		return 0
	}
	return tree.root.countChildren() + 1
}
 
func main() {
	root := &TreeItem{Name: "Max", Age: 5}
	root.left = &TreeItem{Name: "Hans", Age: 3}
	root.right = &TreeItem{Name: "Hermann", Age: 8}
 
	tree := Tree{root}
 
	fmt.Println("Count: ", tree.count())
}
snippets/golang/containers/binarytree.1521626205.txt.gz · Last modified: by allspark