Golang二叉搜索树算法翻译

时间:2015-09-26 16:50:22

标签: go reference tree binary-search-tree

我是Golang的初学者并尝试构建二进制搜索树。我的源代码:

package main

import (
    "fmt"
    "math/rand"
    "time"
)

type Node struct{
    value int
    left *Node
    right *Node
}

func insert(root *Node,v int){
    if root==nil{
        root=&Node{v,nil,nil}
    } else if v<root.value{
        insert(root.left,v)
    } else{
        insert(root.right,v)
    }
}

func inTraverse(root *Node){
    if (root==nil){
        return
    }
    inTraverse(root.left)
    fmt.Printf("%d",root.value)
    inTraverse(root.right)
}

func main() {
    var treeRoot *Node
    rand.Seed(time.Now().UnixNano())
    n:=6
    var a[6]int
    for i:=0;i<n;i++{
        a[i]=rand.Intn(20)+1
    }
    fmt.Println("Array of integer: ")
    for i:=0;i<n;i++{
        fmt.Printf("%d ",a[i])
    }
    fmt.Println()
    for i:=0;i<n;i++{
        insert(treeRoot,a[i])
    }
    inTraverse(treeRoot)
    fmt.Println()
}

结果显示空树。我的代码出了什么问题? Golang是否具有按值传递或按引用传递?请帮我解决这个问题。

1 个答案:

答案 0 :(得分:2)

Go始终按值传递参数。你应该写:

func insert(root *Node,v int) *Node {
    if root == nil{
        root = &Node{v,nil,nil}
    } else if v<root.value{
        root.left = insert(root.left,v)
    } else{
        root.right = insert(root.right,v)
    }
    return root
}

for i:=0;i<n;i++{
    treeRoot = insert(treeRoot,a[i])
}

查看结果:http://play.golang.org/p/94H_l3rfSH

相关问题