-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinarySearchTree.java
More file actions
75 lines (57 loc) · 1.51 KB
/
BinarySearchTree.java
File metadata and controls
75 lines (57 loc) · 1.51 KB
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
public class BinarySearchTree {
public Node root;
public Node search(int target) {
return search(this.root, target);
}
public static Node search(Node root, int target) {
if (root == null) {
return null;
}
if (root.val == target) {
return root;
}
if (root.val > target) {
return search(root.left, target);
}
return search(root.right, target);
}
public void sortedArrayToBST(int[] arr) {
this.root = sortedArrayToBST(arr, 0, arr.length - 1);
}
public static Node sortedArrayToBST(int[] arr, int start, int end) {
if (start > end) {
return null;
}
int mid = start + (end - start) / 2;
Node node = new Node(arr[mid]);
node.left = sortedArrayToBST(arr, start, mid - 1);
node.right = sortedArrayToBST(arr, mid + 1, end);
return node;
}
public void printInorderTraversal() {
printInorderTraversal(this.root);
}
public static void printInorderTraversal(Node node) {
if (node == null) {
return;
}
printInorderTraversal(node.left);
System.out.print(node.val + " ");
printInorderTraversal(node.right);
}
}
class Node {
int val;
Node left;
Node right;
Node() {
}
Node(int val) {
this.val = val;
}
Node(int x, Node left, Node right) {
this.val = x;
this.left = left;
this.right = right;
}
}