2 回答

TA貢獻1821條經驗 獲得超6個贊
好吧,我終于知道你到底在問什么了。
New()
?方法返回一個值,而不是指針,這意味著您看不到調用者以后的更改。調用者得到的只是 Node.js 的一個值副本。所以你打印的父級將永遠是{Left:<nil> Right:<nil> Value:2}
。
所以和addLeftNode()
一樣addRightNode()
。
只需使用指針,而不是價值來實現您的目標。
我認為這只是Visit()
問題所在的方法。
當您在訪問左孩子后立即返回時,它永遠不會訪問右孩子。
左右孩子不互斥,所以第二個 if 子句不應該使用
else if
,應該是if
。訪問順序也有問題。
前:
// Visit will automatically walk through the Child Nodes of the accessed Parent Node.
func (parent *Node) Visit() (Node, int) {
? ? fmt.Println("Node value:", parent.Value)
? ? if parent.hasLeftNode() {
? ? ? ? return parent.Left.Visit()
? ? } else if parent.hasRightNode() {
? ? ? ? return parent.Right.Visit()
? ? }
? ? return *parent, parent.Value
}
修改的:
// Visit will automatically walk through the Child Nodes of the accessed Parent Node.
func (parent *Node) Visit() (Node, int) {
? ? if parent.hasLeftNode() {
? ? ? ? parent.Left.Visit()
? ? }
? ? fmt.Println("Node value:", parent.Value)
? ? if parent.hasRightNode() {
? ? ? ? parent.Right.Visit()
? ? }
? ? return *parent, parent.Value
}
另外,對我來說,Visit()不應該返回任何值。

TA貢獻1856條經驗 獲得超17個贊
前:
// Visit will automatically walk through the Child Nodes of the accessed Parent Node.
func (parent *Node) Visit() (Node, int) {
fmt.Println("Node value:", parent.Value)
if parent.hasLeftNode() {
return parent.Left.Visit()
} else if parent.hasRightNode() {
return parent.Right.Visit()
}
return *parent, parent.Value
}
修改的:
// Visit will automatically walk through the Child Nodes of the accessed Parent Node.
func (parent *Node) Visit() (Node, int) {
if parent.hasLeftNode() {
parent.Left.Visit()
}
fmt.Println("Node value:", parent.Value)
if parent.hasRightNode() {
parent.Right.Visit()
}
return *parent, parent.Value
}
另外,對我來說,Visit()不應該返回任何值。
- 2 回答
- 0 關注
- 236 瀏覽
添加回答
舉報