Skip to content

Commit bc6055c

Browse files
committed
feat: Add solution for LeetCode problem 98
1 parent 4cbc15e commit bc6055c

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
//
2+
// 98. Validate Binary Search Tree
3+
// https://leetcode.com/problems/validate-binary-search-tree/description/
4+
// Dale-Study
5+
//
6+
// Created by WhiteHyun on 2024/06/12.
7+
//
8+
9+
/**
10+
* Definition for a binary tree node.
11+
* public class TreeNode {
12+
* public var val: Int
13+
* public var left: TreeNode?
14+
* public var right: TreeNode?
15+
* public init() { self.val = 0; self.left = nil; self.right = nil; }
16+
* public init(_ val: Int) { self.val = val; self.left = nil; self.right = nil; }
17+
* public init(_ val: Int, _ left: TreeNode?, _ right: TreeNode?) {
18+
* self.val = val
19+
* self.left = left
20+
* self.right = right
21+
* }
22+
* }
23+
*/
24+
class Solution {
25+
func isValidBST(_ node: TreeNode?) -> Bool {
26+
guard let node else { return true }
27+
28+
var left = node.left
29+
var right = node.right
30+
31+
while left?.right != nil {
32+
left = left?.right
33+
}
34+
while right?.left != nil {
35+
right = right?.left
36+
}
37+
38+
if left?.val ?? .min < node.val,
39+
node.val < right?.val ?? .max {
40+
return isValidBST(node.left) && isValidBST(node.right)
41+
}
42+
43+
return false
44+
}
45+
}

0 commit comments

Comments
 (0)