-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path700.SearchinaBinarySearchTree.kt
More file actions
35 lines (31 loc) · 947 Bytes
/
Copy path700.SearchinaBinarySearchTree.kt
File metadata and controls
35 lines (31 loc) · 947 Bytes
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
/**
* Example:
* var ti = TreeNode(5)
* var v = ti.`val`
* Definition for a binary tree node.
* class TreeNode(var `val`: Int) {
* var left: TreeNode? = null
* var right: TreeNode? = null
* }
*/
//https://leetcode.com/problems/search-in-a-binary-search-tree/description/
class Solution {
//recursive
fun searchBST1(root: TreeNode?, `val`: Int): TreeNode? {
if (root == null) return null
if (root.`val` == `val`) return root
if (`val` < root.`val`) return searchBST(root.left, `val`)
return searchBST(root.right, `val`)
}
fun searchBST(root: TreeNode?, `val`: Int): TreeNode? {
var current = root
while (current != null) {
when {
current.`val` == `val` -> return current
current.`val` < `val` -> current = current.right
else -> current = current.left
}
}
return null
}
}