Golang program to implement Binary Tree

老汉-憨憨 · · 718 次点击 · · 开始浏览    
这是一个创建于 的文章,其中的信息可能已经有所发展或是发生改变。

A binary tree is a tree data structure in which each node has at most two child nodes, usually distinguished as "left" and "right". Nodes with children are parent nodes, and child nodes may contain references to their parents. Here is the source code of the Go program to implement Binary Tree


// Binary Tree in Golang

package main

  

import (

    "fmt"

    "os"

    "io"

)

  

type BinaryNode struct {

    left  *BinaryNode

    right *BinaryNode

    data  int64

}

  

type BinaryTree struct {

    root *BinaryNode

}

  

func (t *BinaryTree) insert(data int64) *BinaryTree {

    if t.root == nil {

        t.root = &BinaryNode{data: data, left: nil, right: nil}

    } else {

        t.root.insert(data)

    }

    return t

}

  

func (n *BinaryNode) insert(data int64) {

    if n == nil {

        return

    } else if data <= n.data {

        if n.left == nil {

            n.left = &BinaryNode{data: data, left: nil, right: nil}

        } else {

            n.left.insert(data)

        }

    } else {

        if n.right == nil {

            n.right = &BinaryNode{data: data, left: nil, right: nil}

        } else {

            n.right.insert(data)

        }

    }  

}

  

func print(w io.Writer, node *BinaryNode, ns int, ch rune) {

    if node == nil {

        return

    }

  

    for i := 0; i < ns; i++ {

        fmt.Fprint(w, " ")

    }

    fmt.Fprintf(w, "%c:%v\n", ch, node.data)

    print(w, node.left, ns+2, 'L')

    print(w, node.right, ns+2, 'R')

}

  

func main() {

    tree := &BinaryTree{}

    tree.insert(100).

        insert(-20).

        insert(-50).

        insert(-15).

        insert(-60).

        insert(50).

        insert(60).

        insert(55).

        insert(85).

        insert(15).

        insert(5).

        insert(-10)

    print(os.Stdout, tree.root, 0, 'M')

}
C:\golang\time>go run binarytree.go
M:100
L:-20
L:-50
L:-60
R:-15
R:50
L:15
L:5
L:-10
R:60
L:55
R:85

C:\golang\time>

 


有疑问加站长微信联系(非本文作者)

本文来自:开源中国博客

感谢作者:老汉-憨憨

查看原文:Golang program to implement Binary Tree

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

718 次点击  
加入收藏 微博
0 回复
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传