Swift solution - iterative, recursive


  • 0
    class Solution {
        func isValidBST(_ root: TreeNode?) -> Bool {
            if root == nil {
                return true
            }
            
            var root = root
            var stack = [TreeNode]()
            var prev: TreeNode? = nil
            
            while root != nil || !stack.isEmpty {
                while root != nil {
                    stack.append(root!)
                    root = root?.left
                }
                root = stack.popLast()
                if prev != nil && root!.val <= prev!.val {
                    return false
                }
                prev = root
                root = root?.right
            }
            
            return true
        }
        
        func isValidBST_Rec(_ root: TreeNode?) -> Bool {
            return helper(root, nil, nil)
        }
        
        func helper(_ root: TreeNode?, _ minNode: TreeNode?, _ maxNode: TreeNode?) -> Bool {
            if root == nil {
                return true
            }
            
            if minNode != nil && root!.val <= minNode!.val {
                return false
            }
            if maxNode != nil && root!.val >= maxNode!.val {
                return false
            }
            
            return helper(root?.left, minNode, root) && helper(root?.right, root, maxNode)
        }
    }
    ``

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.