我對如何在golang中正確交換二叉樹感到困惑。假設(shè)我們有低于BSTInput BST1 1 / \ 2 3 / \ / \ 4 5 6 7/ \8 9...output BST2 1 / \ 3 2 / \ / \ 7 6 5 4 / \ 9 8...Why not this? BST3 1 / \ 3 2 / \ / \ 5 4 7 6/ \9 8我已經(jīng)弄清楚下面的代碼將輸出正確的答案,并且我理解交換2和3的工作原理,因為樹首先站在1。但是,當我們開始遞歸時,我們向左移動,現(xiàn)在沒有辦法交換左樹和右樹,例如。由于每次我們經(jīng)歷遞歸(在 內(nèi)部,我們將節(jié)點向左移動),我不確定為什么我們可以交換左樹側(cè)(如4)節(jié)點和右側(cè)(7)節(jié)點。就我目前的理解來看,BST3'似乎是正確的輸出...tree47if tree.Left != niltype BinaryTree struct { Value int Left *BinaryTree Right *BinaryTree}func (tree *BinaryTree) InvertBinaryTree() { tree.Left, tree.Right = tree.Right, tree.Left if tree.Left != nil{ tree.left.InvertBinaryTree } if tree.Right != nil { tree.Right.InvertBinaryTree }
1 回答

滄海一幻覺
TA貢獻1824條經(jīng)驗 獲得超5個贊
您交換的是節(jié)點,而不是它們包含的值。因此,所有的孩子都來了。交換根的子級后,“2”的子項仍將是 4 和 5(一旦交換該節(jié)點的子級,它們將是 5 和 4)。你正在“重新連接”整個結(jié)構(gòu),而不是拿起數(shù)字并將它們放在同一結(jié)構(gòu)中的新位置。
- 1 回答
- 0 關(guān)注
- 97 瀏覽
添加回答
舉報
0/150
提交
取消