英文:
Golang Binary Search Tree Algorithm Translation
问题
我是你的中文翻译助手,以下是你的代码的翻译:
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 是按值传递还是按引用传递?请帮我解决这个问题。
英文:
I'm beginner to Golang and trying to build a Binary Search Tree. My source code to do it:
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()
}
The result shows an empty tree. What's wrong with my code? Does Golang have pass-by-value or pass-by-reference? Please help me solve this.
答案1
得分: 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
英文:
Go always passes parameters by value. You should rather write:
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
}
and:
for i:=0;i<n;i++{
treeRoot = insert(treeRoot,a[i])
}
See the result at: http://play.golang.org/p/94H_l3rfSH
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论