当前位置:网站首页>【LeetCode】98. Verify the binary search tree (2 brushes of wrong questions)

【LeetCode】98. Verify the binary search tree (2 brushes of wrong questions)

2022-07-05 02:20:00 Kaimar

0
1

  • Ideas
    The middle order traversal of binary search tree is a monotonically increasing sequence , Therefore, based on this, we can use the results of the middle order traversal to judge .
var prev *TreeNode = nil //  Previous node 
func isValidBST(root *TreeNode) bool {
    
    if root == nil {
    
        return true
    }
    //  Left 
    left := isValidBST(root.Left)
    //  in 
    if prev != nil && prev.Val >= root.Val {
    
        return false
    }
    prev = root
    //  Right 
    right := isValidBST(root.Right)

    return left && right
}

2
3
Encounter a pit , I can live alone , It's about global variables , Avoid using global variables .

/** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */
func isValidBST(root *TreeNode) bool {
    
    var preNode *TreeNode
    var valid func(node *TreeNode) bool
    valid = func(node *TreeNode) bool {
    
        if node == nil {
    
            return true
        }
        //  Left 
        left := valid(node.Left)
        //  in 
        if preNode != nil && preNode.Val >= node.Val {
    
            return false
        }
        preNode = node
        //  Right 
        right := valid(node.Right)
        return left && right
    }

    return valid(root)
}

4

原网站

版权声明
本文为[Kaimar]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202140933282604.html