-
Notifications
You must be signed in to change notification settings - Fork 0
/
0098.Validate Binary Search Tree.swift
43 lines (37 loc) · 1.22 KB
/
0098.Validate Binary Search Tree.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
/**
* Definition for a binary tree node.
* public class TreeNode {
* public var val: Int
* public var left: TreeNode?
* public var right: TreeNode?
* public init() { self.val = 0; self.left = nil; self.right = nil; }
* public init(_ val: Int) { self.val = val; self.left = nil; self.right = nil; }
* public init(_ val: Int, _ left: TreeNode?, _ right: TreeNode?) {
* self.val = val
* self.left = left
* self.right = right
* }
* }
*/
class Solution {
private let _max = 2147483647 + 1
private let _min = -2147483648 - 1
func isValidBST(_ root: TreeNode?) -> Bool {
return check(root, _min, _max)
}
private func check(_ node: TreeNode?, _ _min: Int, _ _max: Int) -> Bool {
guard let node = node else {
return true
}
if node.val <= _min || node.val >= _max {
return false
}
if let left = node.left, left.val >= node.val {
return false
}
if let right = node.right, right.val <= node.val {
return false
}
return check(node.left, _min, node.val) && check(node.right, node.val, _max)
}
}