-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinarySearchTree.java
More file actions
127 lines (105 loc) · 2.85 KB
/
BinarySearchTree.java
File metadata and controls
127 lines (105 loc) · 2.85 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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
import java.util.*;
/**
* A class to create a binary tree
* @author Jake Model
*/
public class BinarySearchTree {
private Node root;
private int nodeCount = 0;
// Constructor for the class
public BinarySearchTree() {
root = null;
}
/**
* Get root
* @return root of BST
*/
public Node getRoot() {
return root;
}
/**
* Get node cound
* @return node count
*/
public int getNodeCount() {
return nodeCount;
}
/**
* Insert a node in the BST
* @param Node node, int key
*/
public void insert(Node node, int key) {
// Add to total count of nodes
nodeCount++;
// Find the parent
Node parent = null;
Node index = root;
while (index != null) {
parent = index;
if (key < index.getKey())
index = index.getLeft();
else
index = index.getRight();
}
// Insert child
if (parent == null)
root = new Node(key);
else if (key < parent.getKey())
parent.setLeft(new Node(key));
else
parent.setRight(new Node(key));
}
/**
* Preorder traversal of BST
* @param Node root
*/
public void preorderRec(Node root) {
if (root == null)
return;
// Left side
preorderRec(root.getLeft());
// Right side
preorderRec(root.getRight());
}
/**
* Find sum of all keys of BST
* @param Node root
* @return sum of all keys
*/
public int sum(Node root) {
if (root == null)
return 0;
else
return root.getKey() + sum(root.getLeft()) + sum(root.getRight());
}
/**
* Find the k'th biggest element in BST
* @param Node root, int input
* @throws IndexOutOfBoundsException if input too large
* @return kth-biggest node of BST
*/
public Node kthBiggest(Node root, int input) throws IndexOutOfBoundsException {
if (input > (getNodeCount() + 1)) {
System.out.println("Index out of range");
throw new IndexOutOfBoundsException();
}
// Initialize an array list of Nodes
List<Node> reverseList = new ArrayList<>();
reverseInord(root, reverseList);
return reverseList.get(getNodeCount() - input + 1);
}
/**
* Private method, computes reverse inorder
* @param Node root, List<Node> reverseList
*/
private void reverseInord(Node root, List<Node> reverseList) {
if (root == null)
return;
// Left side
reverseInord(root.getLeft(), reverseList);
// Current node
reverseList.add(root);
// Right side
reverseInord(root.getRight(), reverseList);
}
}