User Tools

Site Tools


snippets:golang:containers:binarytree

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 (tree *Tree) findByAge(age int) *TreeItem {
	if tree.root == nil {
		return nil
	}
 
	item := tree.root
	for item != nil && item.Age != age {
		if item.Age < age {
			item = item.right
		} else if item.Age > age {
			item = item.left
		}
	}
 
	if item != nil && item.Age == age {
		return item
	}
	return nil
}
 
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())
 
	f := tree.findByAge(9)
	fmt.Println(f)
}
snippets/golang/containers/binarytree.txt · Last modified: by allspark