-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSearchInBinarySearchTree.java
More file actions
37 lines (32 loc) · 927 Bytes
/
SearchInBinarySearchTree.java
File metadata and controls
37 lines (32 loc) · 927 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
36
37
package binary_search_tree;
/**
* Description: https://leetcode.com/problems/search-in-a-binary-search-tree
* Difficulty: Easy
*/
public class SearchInBinarySearchTree {
/**
* Time complexity: O(h)
* Space complexity: O(1)
*/
public TreeNode searchBSTViaIteration(TreeNode root, int val) {
while (root != null && root.val != val) {
root = root.val > val ? root.left : root.right;
}
return root;
}
/**
* Time complexity: O(h)
* Space complexity: O(h)
*/
public TreeNode searchBSTViaRecursion(TreeNode root, int val) {
if (root == null || root.val == val) return root;
return root.val > val
? searchBSTViaRecursion(root.left, val)
: searchBSTViaRecursion(root.right, val);
}
private static class TreeNode {
int val;
TreeNode left;
TreeNode right;
}
}