Golong 切片 函数返回时怎么就清空了 力扣刷题遇到的问题


package main

import "fmt"
//验证二叉搜索树
//给你一个二叉树的根节点 root ,判断其是否是一个有效的二叉搜索树。
//
//有效 二叉搜索树定义如下:
//
//节点的左子树只包含 小于 当前节点的数。
//节点的右子树只包含 大于 当前节点的数。
//所有左子树和右子树自身必须也是二叉搜索树。

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

func main() {
    root := &TreeNode{5, nil, nil}
    root.Right = &TreeNode{4, nil, nil}
    root.Right.Left = &TreeNode{3, nil, nil}
    root.Right.Right = &TreeNode{64, nil, nil}
    root.Left = &TreeNode{1, nil, nil}
    fmt.Print(isValidBST(root))
}
func isValidBST(root *TreeNode) (ww bool) {
    var reverse func(node *TreeNode, ww *bool) (res []int)
    reverse = func(node *TreeNode, ww *bool) (res []int) {
        //退出条件
        if node == nil {
            return
        }
        //主要递归判断
        reverse(node.Left, ww)
        res = append(res, node.Val)
        //就是这里 下面这个if永远不会进去 ,res里每次只有一个数据 问题出在哪??
        if len(res) >= 2 {
            if res[len(res)-1] < res[len(res)-2] {
                *ww = false
            }
        }
        reverse(node.Right, ww)
        return
    }
    ww = true
    reverse(root, &ww)
    return ww
}

你调用reverse函数后没有接收切片的返回值啊,你要接收一下返回值。或者将切片指针作为形参,就不用接收了。

应该是你的res是局部变量。局部变量的地址在函数结束时,会被自动清除。