亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在Golang中實現二叉樹的中序遍歷

如何在Golang中實現二叉樹的中序遍歷

Go
斯蒂芬大帝 2023-06-26 17:58:29
我正在嘗試在 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)

        }

    }

}


查看完整回答
反對 回復 2023-06-26
  • 1 回答
  • 0 關注
  • 168 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號