我发现 go 好像有个 bug

8次阅读

共计 852 个字符,预计需要花费 3 分钟才能阅读完成。

我先上代码


type TreeNode struct {
	Val   int
	Left  *TreeNode
	Right *TreeNode
}

func Solution199(root *TreeNode) []int {return dfs199(root, []int{})
}	

func dfs199(root *TreeNode,ans []int)[]int{
	if root == nil{return ans}
	new := append(ans,root.Val)

	right := dfs199(root.Right,new)

	left := dfs199(root.Left,new)


	fmt.Println(root.Val,":")
	if root.Right != nil{fmt.Println(root.Right.Val,right)
	}
	if root.Left != nil{fmt.Println(root.Left.Val,left)
	}



	result := right
	if len(left) > len(right){result = append(result,left[len(right):]...)
	}
	fmt.Println(result)
	return result
}

func main() {
	root := &tree.TreeNode{
		Val: 1,
		Left: nil,
		Right: &tree.TreeNode{
			Val: 5,
			Left: &tree.TreeNode{
				Val: 3,
				Left: &tree.TreeNode{
					Val: 2,
					Left: nil,
					Right: nil,
				},
				Right: &tree.TreeNode{
					Val: 4,
					Left: nil,
					Right: nil,
				},
			},
			Right: nil,
		},
	}
	fmt.Println(tree.Solution199(root))
}

我发现 当递归到 3 这个节点的时候,right 这个数组 通过 dfs199 函数递归后得到是 1534,但是当下一个 left 这个数组 通过 dfs199 函数递归后得到 1532 的时候,right 也会跟着变成 1532 这是为什么呢?

正文完
 0