Golang program to implement Binary Tree

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

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

Binary Tree in Golangpackage 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 {      & nbsp; 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 (+).         insert ( -20) .         insert ( -50).         insert (-15).         insert ( -60) .         Insert (        insert) .         insert (        insert) .         insert (&NBSP;&NBSP;&NBSP;&N).Bsp;    insert (5).         insert ( -10)      print (OS. Stdout, Tree.root, 0, ' M ')}
C:\golang\time>go run binarytree.goM:100L:-20L:-50L:-60R:-15R:50L:15L:5L:-10R:60L:55R:85C:\golang\time>

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.