我正在嘗試在 Golang 中實現一個簡單的二叉樹,以便理解課堂上教授的概念。我對 Golang 有點陌生,但同時,我很難理解遞歸的概念以及在哪里插入下一個節點。package mainimport "fmt"type Node struct { data int right *Node left *Node}func main(){ //driver code //this is the root of the tree root := Node{data:6} //set the data to the int //set the right and left pointers to null /* 6 / \ nil nil */ n1 := Node{data: 8} n2 := Node{data: 4} n3 := Node{data: 10} root.insert(&n1) root.insert(&n2) root.insert(&n3) inorder(&root)}func (n *Node) insert(newNode *Node){ if n.left == nil && newNode.data < n.data { fmt.Println("added to the left") }else if n.right == nil && newNode.data > n.data { fmt.Println("added to the right") }else{ print("recurse") n.insert(newNode) }}func inorder(rt *Node){ if rt == nil { fmt.Print("|") return } inorder(rt.left) fmt.Print(rt.data) inorder(rt.right)}我得到的輸出是:added to the rightadded to the leftadded to the right|6|預期輸出應該是:added to the rightadded to the leftrecurseadded to the right4 6 8 10任何幫助是極大的贊賞。
1 回答

料青山看我應如是
TA貢獻1772條經驗 獲得超8個贊
此代碼將在右側插入重復項。您可能想忽略重復項(帶有注釋掉的行)。
func (n *Node) insert(newNode *Node){
if newNode.data < n.data {
if n.left == nil {
n.left = newNode
} else {
n.left.insert(newNode)
}
} else {
//} else if newNode.data > n.data {
if n.right == nil {
n.right = newNode
} else {
n.right.insert(newNode)
}
}
}
- 1 回答
- 0 關注
- 168 瀏覽
添加回答
舉報
0/150
提交
取消