Skip to content

Commit 8e0008d

Browse files
committed
Add validate binary search tree solution
1 parent a005de9 commit 8e0008d

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
/**
2+
* Example:
3+
* var ti = TreeNode(5)
4+
* var v = ti.`val`
5+
* Definition for a binary tree node.
6+
* class TreeNode(var `val`: Int) {
7+
* var left: TreeNode? = null
8+
* var right: TreeNode? = null
9+
* }
10+
*/
11+
class Solution {
12+
fun isValidBST(root: TreeNode?): Boolean {
13+
val values = mutableListOf<Int>()
14+
inorderTraversal(root, values)
15+
16+
for (i in 1 until values.size) {
17+
if (values[i] <= values[i - 1]) return false
18+
}
19+
20+
return true
21+
}
22+
23+
private fun inorderTraversal(root: TreeNode?, values: MutableList<Int>) {
24+
if (root == null) return
25+
26+
inorderTraversal(root.left, values)
27+
values.add(root.`val`)
28+
inorderTraversal(root.right, values)
29+
}
30+
}

0 commit comments

Comments
 (0)