File tree Expand file tree Collapse file tree 1 file changed +49
-0
lines changed
src/main/kotlin/leetcode/validate-binary-search-tree Expand file tree Collapse file tree 1 file changed +49
-0
lines changed Original file line number Diff line number Diff line change
1
+ package leetcode.`validate-binary-search-tree`
2
+
3
+ import TreeNode
4
+ import org.junit.Test
5
+
6
+ class Solution {
7
+ fun isValidBST (root : TreeNode ? ): Boolean {
8
+ return process(root)!! .isBST
9
+ }
10
+
11
+ private fun process (node : TreeNode ? ): ReturnType ? {
12
+ if (node == null ) return null
13
+
14
+ val left = process(node.left)
15
+ val right = process(node.right)
16
+
17
+ var min: Int = node.`val `
18
+ var max: Int = node.`val `
19
+ var isBST = true
20
+ if (left != null ) {
21
+ min = Math .min(left.min, node.`val `)
22
+ max = Math .max(left.max, node.`val `)
23
+ isBST = left.isBST && node.`val ` > left.max
24
+ }
25
+ if (right != null ) {
26
+ min = Math .min(right.min, min)
27
+ max = Math .max(right.max, max)
28
+ isBST = isBST && right.isBST && node.`val ` < right.min
29
+ }
30
+
31
+ return ReturnType (isBST, min, max)
32
+ }
33
+
34
+ class ReturnType (var isBST : Boolean , var min : Int , var max : Int )
35
+
36
+ @Test
37
+ fun test (){
38
+ val node1 = TreeNode (5 )
39
+ val node2 = TreeNode (4 )
40
+ val node3 = TreeNode (6 )
41
+ val node4 = TreeNode (3 )
42
+ val node5 = TreeNode (7 )
43
+ node1.left = node2
44
+ node1.right = node3
45
+ node3.left = node4
46
+ node3.right = node5
47
+ isValidBST(node1)
48
+ }
49
+ }
You can’t perform that action at this time.
0 commit comments