Golang implementation of a two-fork search tree

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

Now it is only simple to add, find, traverse. There will be perfect after the time.

Package Mainimport "FMT" type BNode struct {data intleft *bnoderight *bnode}type Tree struct {firstnode *bnode}func (t *tree) printdata (node *bnode) {if node.left! = nil {t.printdata (node.left)}fmt. Println (node.data) if node.right! = nil {t.printdata (node.right)}return}//return Nodefunc (t *tree) Search (data int, BNode *bn Ode) *bnode {if BNode = nil {return nil}if data > Bnode.data {return t.search (data, bnode.right)} else if data < Bn Ode.data {return T.search (data, Bnode.left)} else if data = = Bnode.data {return Bnode}return nil}func (t *tree) Insert (dat A int, CurrentNode *bnode) {newNode: = &bnode{data,nil,nil,}if T.firstnode = nil {T.firstnode = Newnodereturn}if t.Se Arch (data, t.firstnode)! = nil {Panic ("The data already exists") Return}if data > Currentnode.data {if currentnode.right = nil {current Node.right = NewNode} else {T.insert (data,currentnode.right)}} or else if data < Currentnode.data {if currentnode.left = = Nil {currentnode.left = NewNode} else {T.insert (data, CURRENTNODE.LEFT)}}return}func Main () {nodes: = []int{4,1,7,15,10}tree: = Tree{}for _, Data: = Range nodes {tree. Insert (data, tree. Firstnode)}tree. Printdata (tree. Firstnode) fmt. Print (tree. Search (tree). Firstnode))}

 

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.