第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

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

如何在Golang中實現(xiàn)二叉樹的中序遍歷

如何在Golang中實現(xiàn)二叉樹的中序遍歷

Go
斯蒂芬大帝 2023-06-26 17:58:29
我正在嘗試在 Golang 中實現(xiàn)一個簡單的二叉樹,以便理解課堂上教授的概念。我對 Golang 有點陌生,但同時,我很難理解遞歸的概念以及在哪里插入下一個節(jié)點。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|預(yù)期輸出應(yīng)該是:added to the rightadded to the leftrecurseadded to the right4 6 8 10任何幫助是極大的贊賞。
查看完整描述

1 回答

?
料青山看我應(yīng)如是

TA貢獻1772條經(jīng)驗 獲得超8個贊

此代碼將在右側(cè)插入重復(fù)項。您可能想忽略重復(fù)項(帶有注釋掉的行)。


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)

        }

    }

}


查看完整回答
反對 回復(fù) 2023-06-26
  • 1 回答
  • 0 關(guān)注
  • 181 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號