Skip to content

Commit b1adfbe

Browse files
committedDec 25, 2023
add lab7
1 parent 954bcb3 commit b1adfbe

31 files changed

+1327
-0
lines changed
 

‎.DS_Store

0 Bytes
Binary file not shown.

‎LAB7_BinarySearchTree/.DS_Store

6 KB
Binary file not shown.

‎LAB7_BinarySearchTree/.idea/.gitignore

+3
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎LAB7_BinarySearchTree/.idea/checkstyle-idea.xml

+15
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎LAB7_BinarySearchTree/.idea/misc.xml

+6
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎LAB7_BinarySearchTree/.idea/modules.xml

+8
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
<?xml version="1.0" encoding="UTF-8"?>
2+
<module type="JAVA_MODULE" version="4">
3+
<component name="CheckStyle-IDEA-Module" serialisationVersion="2">
4+
<option name="activeLocationsIds" />
5+
</component>
6+
<component name="NewModuleRootManager" inherit-compiler-output="true">
7+
<exclude-output />
8+
<content url="file://$MODULE_DIR$">
9+
<sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
10+
</content>
11+
<orderEntry type="inheritedJdk" />
12+
<orderEntry type="sourceFolder" forTests="false" />
13+
</component>
14+
</module>
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
385 KB
Loading
365 KB
Loading

‎LAB7_BinarySearchTree/png/delete.png

293 KB
Loading
299 KB
Loading
276 KB
Loading

‎LAB7_BinarySearchTree/png/insert.png

323 KB
Loading

‎LAB7_BinarySearchTree/src/BST.java

+275
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,275 @@
1+
public class BST<T extends Comparable<T>> extends BT<T> {
2+
/** Create an empty binary tree */
3+
public BST() {
4+
5+
}
6+
7+
/** Create a binary tree from an object */
8+
public BST(T object) {
9+
root.element = object;
10+
}
11+
12+
/** Create a binary tree from an array of objects */
13+
public BST(T[] objects) {
14+
for (int i = 0; i < objects.length; i++)
15+
insert(objects[i]);
16+
}
17+
18+
// ----------------------------------------------
19+
/**
20+
* Insert newdata into the binary search tree
21+
*/
22+
public void insert(T newdata) {
23+
// Ex1: Complete this program
24+
if (root == null) {
25+
// Create a new root
26+
root = new BTNode<T>(newdata);
27+
} else {
28+
// Locate the parent node
29+
BTNode<T> parent = null;
30+
BTNode<T> current = root;
31+
// insert your code
32+
while(current != null){
33+
parent = current;
34+
if (newdata.compareTo(current.element) <= 0){ //if newdata <= current, go left
35+
current = current.left;
36+
}
37+
else if (newdata.compareTo(current.element) > 0){ //if newdata > current, go right
38+
current = current.right;
39+
}
40+
}
41+
//when current == null (the leaf node)
42+
if (newdata.compareTo(parent.element) <= 0){ //to insert the newnode
43+
parent.left = new BTNode<T>(newdata); //if newnode <= its parent, assign newnode to left
44+
}
45+
else {
46+
parent.right = new BTNode<T>(newdata); //if newnode > its parent, assign newnode to right
47+
}
48+
}
49+
50+
size++;
51+
}
52+
53+
// ----------------------------------------------
54+
/**
55+
* Delete data from the binary search tree
56+
*/
57+
// Ex2. Complete This Program
58+
public T delete(T item) {
59+
// Locate the node to be deleted and also locate its parent node
60+
BTNode<T> parent = null;
61+
BTNode<T> current = root;
62+
63+
boolean currentIsLeftChild = true;
64+
65+
while (current != null) {
66+
// insert your code
67+
//we need to search for the deleted node first
68+
if(item.compareTo(current.element) < 0){ //if item < current element, go left
69+
parent = current;
70+
current = current.left;
71+
currentIsLeftChild = true;
72+
73+
}
74+
else if (item.compareTo(current.element) > 0){ //if item > current element, go right
75+
parent = current;
76+
current = current.right;
77+
currentIsLeftChild = false;
78+
}
79+
else {
80+
break;
81+
}
82+
}
83+
84+
// Case 0: item is not in the tree
85+
if (current == null) {
86+
return null;
87+
}
88+
89+
T temp = current.element;
90+
// Case 1: current is the leave
91+
92+
if (current.left == null && current.right == null) {
93+
// insert your code
94+
if(currentIsLeftChild){
95+
parent.left = null;
96+
}
97+
else {
98+
parent.right = null;
99+
}
100+
}
101+
102+
// Case 2: If the deleted node has one child
103+
// Case 2.1: if its child node is on the right
104+
if ((current.left == null)) { // If only has one right child or no children.
105+
if (currentIsLeftChild) {
106+
// insert your code
107+
if(parent == null){ //it is the root (if deleting root)
108+
root = current.right; //there's no leftsub for the previous root, so when it deleted the root,
109+
// the right child of the root will be the next root
110+
}
111+
else { //it is not the root, current is left child, it has no current.left so when it deleted current,
112+
// it has to link parent.left with the current.right
113+
parent.left = current.right;
114+
current.right = null; //disconnect the link of temp(current)
115+
}
116+
117+
} else { //current is right child
118+
// insert your code
119+
if(parent == null){ //it is the root (if deleting root)
120+
root = current.right; //there's no leftsub for the previous root, so when it deleted the root,
121+
// the right child of the root will be the next root
122+
}
123+
else { //it is not root, current is right child, it has np current.left so when it deleted current,
124+
// it has to link parent.right with the current.right
125+
parent.right = current.right;
126+
current.right = null; //disconnect the link of temp(current)
127+
}
128+
}
129+
}
130+
// Case 2.2: If its child node is on the left
131+
else if ((current.right == null)) { // Only one left child
132+
if (currentIsLeftChild) {
133+
// insert your code
134+
if (parent == null){ //it is the root (if deleting root)
135+
root = current.left; //there's no rightsub for the previous root, so when it deleted the root,
136+
// the left child of the root will be the next root
137+
}
138+
else{ //it is not root, current is left child, it has no current.right so when it deleted current,
139+
// it has to link parent.left with the current.left
140+
parent.left = current.left;
141+
current.left = null; //disconnect the link of temp(current)
142+
143+
}
144+
} else { //current is right child
145+
// insert your code
146+
if (parent == null){ //it is the root (if deleting root)
147+
root = current.left; //there's no rightsub for the previous root, so when it deleted the root,
148+
// the left child of the root will be the next root
149+
}
150+
else{ //it is not root, current is right child, it has no current.right so when it deleted current,
151+
// it has to link parent.right with the current.left
152+
parent.right = current.left;
153+
current.left = null; //disconnect the link of temp(current)
154+
}
155+
}
156+
} else { // Case 3: Have both children
157+
BTNode<T> maxleft = current.left;
158+
BTNode<T> maxleftParent = current;
159+
while (maxleft.right != null) {
160+
maxleftParent = maxleft;
161+
maxleft = maxleft.right;
162+
}
163+
current.element = maxleft.element; //replace the temp(current) with maxleft
164+
if (maxleft.left == null && maxleft.right == null) { // Case 3.1 if maxleft is a leave,
165+
// then replace the temp(current) with maxleft, then set maxleftParent to have no child (unlink)
166+
//insert your code
167+
maxleftParent.right = null; //unlink maxleftParent with maxleft
168+
}
169+
else if (maxleft.left != null) { // Case 3.2 if maxleft has a left child,
170+
// then replace the temp(current) with maxleft, make maxleft.left be the right child of maxleftParent
171+
//insert your code
172+
maxleftParent.right = maxleft.left; //connect maxleftParent with maxleft.left
173+
maxleft.left = null; //unlink maxleft with maxleft.left
174+
}
175+
else if (maxleftParent == current) { // Case 3.3 if maxleft is leftchild of current,
176+
// then replace the temp(current) with maxleft, make maxleft.left be the leftchild of temp(current.left)
177+
//insert your code
178+
current.left = maxleft.left; //connect temp(current) with maxleft.left
179+
maxleft.left = null; //unlink maxleft with maxleft.left
180+
}
181+
}
182+
size--;
183+
return temp;
184+
}
185+
// ---------------------------------------------------------
186+
187+
// Search for the data returns true if it finds the data or otherwise false
188+
public boolean search(T data) {
189+
// Ex 3: Complete this section.
190+
//replace the following line with your code
191+
BTNode<T> current = root;
192+
while (current != null){
193+
if (data.compareTo(current.element) < 0) { //if data <= current, go left in search we compare just for < 0
194+
//if we use <= 0 it'll haas a problem when it matches, it will continue going left but it should stop there so we need to use < 0zsz
195+
current = current.left;
196+
}
197+
else if (data.compareTo(current.element) > 0) { //if newdata > current, go right
198+
current = current.right;
199+
}
200+
else { //element matches with current.element
201+
return true;
202+
}
203+
}
204+
return false;
205+
}
206+
207+
// ---------------------------------------------------------
208+
209+
BTNode<T> findSmallest() {
210+
return findSmallest(root);
211+
}
212+
213+
// ----------------------------------------------
214+
BTNode<T> findSmallest(BTNode<T> start) {
215+
// Ex 4: Complete this section.
216+
//replace the following line with your code
217+
BTNode<T> smallest = start;
218+
while (smallest.left != null) {
219+
smallest = smallest.left;
220+
}
221+
if (smallest.left == null){
222+
return smallest;
223+
}
224+
else {
225+
return null;
226+
}
227+
}
228+
229+
// ----------------------------------------------
230+
BTNode<T> findLargest() {
231+
return findLargest(root);
232+
}
233+
234+
// ----------------------------------------------
235+
BTNode<T> findLargest(BTNode<T> start) {
236+
// Ex 5: Complete this section.
237+
//replace the following line with your code
238+
BTNode<T> largest = start;
239+
while (largest.right != null){
240+
largest = largest.right;
241+
}
242+
if (largest.right == null){
243+
return largest;
244+
}
245+
else {
246+
return null;
247+
}
248+
}
249+
250+
/** Get the number of nodes in the tree */
251+
public int getSize() {
252+
return size;
253+
}
254+
255+
/** Returns the root of the tree */
256+
public BTNode getRoot() {
257+
return root;
258+
}
259+
260+
/** Returns a path from the root leading to the specified element */
261+
public java.util.ArrayList<BTNode<T>> path(T e) {
262+
java.util.ArrayList<BTNode<T>> list = new java.util.ArrayList<BTNode<T>>();
263+
BTNode<T> current = root; // Start from the root
264+
265+
while (current != null) {
266+
list.add(current); // Add the node to the list
267+
if (e.compareTo(current.element) < 0) {
268+
current = current.left;
269+
} else if (e.compareTo(current.element) > 0) {
270+
current = current.right;
271+
} else
272+
break;
273+
}
274+
275+
return list; // Retur

‎LAB7_BinarySearchTree/src/BT.java

+274
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,274 @@
1+
/*
2+
* To change this template, choose Tools | Templates
3+
* and open the template in the editor.
4+
*/
5+
6+
import static java.lang.Math.max;
7+
8+
public class BT<T> {
9+
10+
int size;
11+
BTNode<T> root = null;
12+
13+
BT() {
14+
root = null;
15+
size = 0;
16+
}
17+
18+
BT(T data) { //Similar to creating BTNode, it is eventually to create a node
19+
this(new BTNode<T>(data));
20+
}
21+
22+
BT(BTNode<T> root) { //create a node by using root of the stack we have
23+
this.root = root;
24+
size = 1;
25+
}
26+
27+
BT(BTNode<T> root, BT<T> Lsubtree, BT<T> Rsubtree) {
28+
this.root = root;
29+
root.left = Lsubtree.root;
30+
root.right = Rsubtree.root;
31+
size = Lsubtree.size + Rsubtree.size + 1;
32+
}
33+
34+
int findHeight() {
35+
return findHeight(root);
36+
}
37+
38+
int findHeight(BTNode<T> root) {
39+
// Exercise 1 ////////////////
40+
if (root == null) {
41+
// Replace the following statement with your code.
42+
return 0;
43+
} else if (isLeaf(root)) {
44+
// Replace the following statement with your code.
45+
return 1;
46+
} else {
47+
// Replace the following statement with your code.
48+
return 1 + max(findHeight(root.left), findHeight(root.right));
49+
}
50+
}
51+
52+
boolean isLeaf(BTNode<T> root) {
53+
if (root != null && root.left == null && root.right == null) {
54+
return true;
55+
}
56+
else {
57+
return false;
58+
}
59+
}
60+
61+
boolean isBalanced() {
62+
return isBalanced(root);
63+
}
64+
65+
boolean isBalanced(BTNode<T> root) {
66+
if (root == null) {
67+
return true;
68+
}
69+
int LH = findHeight(root.left);
70+
int RH = findHeight(root.right);
71+
int B = Math.abs(LH - RH);
72+
73+
if (B <= 1) {
74+
return (isBalanced(root.left) && isBalanced(root.right));
75+
}
76+
else {
77+
return false;
78+
}
79+
}
80+
81+
/* Inorder traversal from the root */
82+
public void inorder() { //for the other classes to access and use this method
83+
inorder(root);
84+
}
85+
86+
/* Inorder traversal from a subtree */
87+
protected void inorder(BTNode<T> root) {
88+
// Exercise 2 (a) Complete this method
89+
if (root != null) {
90+
if (isLeaf(root)){
91+
System.out.println(root.element + " ");
92+
} else{
93+
inorder(root.left);
94+
System.out.println(root.element + " ");
95+
inorder(root.right);
96+
}
97+
}
98+
}
99+
100+
/* Postorder traversal from the root */
101+
public void postorder() {
102+
postorder(root);
103+
}
104+
105+
/* Postorder traversal from a subtree */
106+
protected void postorder(BTNode<T> root) {
107+
// Exercise 2 (b) Complete this method
108+
if (root != null){
109+
if(isLeaf(root)){
110+
System.out.println(root.element + " ");
111+
} else {
112+
postorder(root.left);
113+
postorder(root.right);
114+
System.out.println(root.element + " ");
115+
}
116+
}
117+
}
118+
119+
/* Preorder traversal from the root */
120+
public void preorder() {
121+
preorder(root);
122+
}
123+
124+
/* Preorder traversal from a subtree */
125+
protected void preorder(BTNode<T> root) {
126+
if (root != null) {
127+
if (isLeaf(root)) {
128+
System.out.print(root.element + " ");
129+
}
130+
else {
131+
System.out.print(root.element + " ");
132+
preorder(root.left);
133+
preorder(root.right);
134+
}
135+
}
136+
}
137+
138+
void PrintDFT() {
139+
// Exercise 3 ////////////////
140+
Stack<BTNode<T>> S = new Stack<BTNode<T>>();
141+
142+
BTNode<T> tmp;
143+
S.push(root); //insert the root to S
144+
//insert your code here
145+
while(!S.isEmpty()){
146+
tmp = S.pop();
147+
if (tmp.right != null){
148+
S.push(tmp.right);
149+
}
150+
if (tmp.left != null){
151+
S.push(tmp.left);
152+
}
153+
System.out.print(tmp.element + " ");
154+
}
155+
}
156+
157+
void PrintBFT() {
158+
// Exercise 4 ////////////////
159+
Queue<BTNode<T>> Q = new Queue<BTNode<T>>();
160+
161+
BTNode<T> tmp;
162+
Q.enqueue(root); //Insert the root to Q
163+
//insert your code here
164+
while(!Q.isEmpty()){
165+
tmp = Q.dequeue();
166+
if (tmp.left != null){
167+
Q.enqueue(tmp.left);
168+
}
169+
if (tmp.right != null){
170+
Q.enqueue(tmp.right);
171+
}
172+
System.out.println(tmp.element);
173+
}
174+
}
175+
176+
static boolean hasHigherPriority(String sign1, String sign2) {
177+
if (sign2.equals("("))
178+
return true;
179+
else if (sign1.equals("*") && sign2.equals("+"))
180+
return true;
181+
else if (sign1.equals("*") && sign2.equals("-"))
182+
return true;
183+
else if (sign1.equals("/") && sign2.equals("+"))
184+
return true;
185+
else if (sign1.equals("/") && sign2.equals("-"))
186+
return true;
187+
else if (sign1.equals("%") && sign2.equals("+"))
188+
return true;
189+
else if (sign1.equals("%") && sign2.equals("-"))
190+
return true;
191+
else
192+
return false;
193+
194+
}
195+
196+
// Exercise 5 ///////////////////////////////////////////////
197+
public static boolean isOperator(String item)
198+
{
199+
if (item.equals("+") || item.equals("-") || item.equals("*") || item.equals("/") || item.equals("%"))
200+
return true;
201+
else
202+
return false;
203+
}
204+
205+
206+
207+
public static BT<String> makeExpressionTree(String [] infixArr)
208+
{
209+
Stack<BT<String>> BTStack = new Stack<BT<String>>(); //for keeping tree stack (value)
210+
Stack<BTNode<String>> parent = new Stack<BTNode<String>>(); //for keeping parent nodes, which is operator
211+
String item;
212+
int i=0;
213+
while(i!=infixArr.length){
214+
item = infixArr[i]; //read item from array
215+
// Case 1: if item it is an open parenthesis
216+
if (item.equals("(")) {
217+
//add your code here
218+
parent.push(new BTNode<String>(item)); //create an operator stack, push it to the stack
219+
}
220+
else if (isOperator(item)){ //if item is an operator
221+
BTNode<String> temp = new BTNode<String>(item); //temp is an item node
222+
if (parent.isEmpty()) { // stack is empty
223+
// add your code here
224+
parent.push(temp);
225+
}
226+
else {// stack is not empty
227+
228+
if(hasHigherPriority(item, parent.peek().element)) {
229+
// add your code here
230+
parent.push(temp);
231+
}
232+
else { //if it isn't higher priority, then we have to calculate it
233+
// add your code here
234+
BTNode<String> root = parent.pop(); //root is an operator
235+
BT<String> Right = BTStack.pop(); //top is Y as the right operand
236+
BT<String> Left = BTStack.pop(); //below top is X as the left operand
237+
//operation: X (operator) P
238+
BTStack.push(new BT<String>(root, Left, Right)); //push this node to tree stack
239+
240+
parent.push(new BTNode<String>(item)); //push item to operand stack
241+
242+
}
243+
}
244+
}
245+
// Case3: if item is a close parenthesis
246+
else if (item.equals(")")) {
247+
while (parent.peek().element.equals("(") == false) {
248+
BTNode<String> root = parent.pop();
249+
BT<String> Rsubtree = BTStack.pop();
250+
BT<String> Lsubtree = BTStack.pop();
251+
BT<String> newBT = new BT<String>(root, Lsubtree, Rsubtree);
252+
BTStack.push(newBT);
253+
}
254+
parent.pop(); //pop from operand stack
255+
}
256+
else {// Case 4: it is not an operator (it is a value)
257+
BT<String> newTree = new BT<String>(item);
258+
// add your code here
259+
BTStack.push(newTree);
260+
261+
}
262+
i++;
263+
}
264+
while (!parent.isEmpty()) { //if operator stack is not empty
265+
BTNode<String> root = parent.pop();
266+
BT<String> Rsubtree = BTStack.pop();
267+
BT<String> Lsubtree = BTStack.pop();
268+
BT<String> newBT = new BT<String>(root, Lsubtree, Rsubtree);
269+
// add your code here
270+
BTStack.push(newBT);
271+
}
272+
return BTStack.pop(); //return the last result value
273+
}
274+
}

‎LAB7_BinarySearchTree/src/BTNode.java

+11
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
public class BTNode<T>
2+
{
3+
T element;
4+
BTNode<T> left = null;
5+
BTNode<T> right = null;
6+
7+
public BTNode(T e)
8+
{
9+
element = e;
10+
}
11+
}

‎LAB7_BinarySearchTree/src/Node.java

+28
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
/**
2+
* The {@code Node} class represents a node in a singly linked list.
3+
*
4+
* @param <T> The type of data stored in the node.
5+
*/
6+
class Node<T> {
7+
/**
8+
* The data element stored in the node.
9+
*/
10+
T element;
11+
12+
/**
13+
* Reference to the next node in the linked list.
14+
*/
15+
Node<T> next;
16+
17+
/**
18+
* Constructs a new node with the specified data element.
19+
*
20+
* @param element The data element to store in the node.
21+
*/
22+
23+
Node(T element) {
24+
this.element = element;
25+
next = null;
26+
}
27+
28+
}

‎LAB7_BinarySearchTree/src/Queue.java

+125
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,125 @@
1+
/**
2+
* A generic queue implementation using a singly linked list.
3+
*
4+
* @param <T> the type of elements stored in the queue
5+
*/
6+
public class Queue<T> {
7+
/** The underlying singly linked list for the queue. */
8+
SList<T> list = new SList<T>();
9+
10+
/** Default constructor to initialize an empty queue. */
11+
Queue() {
12+
}
13+
14+
/**
15+
* Enqueues an element into the queue.
16+
*
17+
* @param element the element to enqueue
18+
*/
19+
void enqueue(T element) {
20+
// Exercise 1a
21+
list.addLast(element);
22+
}
23+
24+
/**
25+
* Dequeues an element from the queue.
26+
*
27+
* @return the dequeued element
28+
*/
29+
T dequeue() {
30+
// Exercise 1b
31+
return list.removeFirst();
32+
}
33+
34+
/**
35+
* Gets the element at the front of the queue without removing it.
36+
*
37+
* @return the element at the front of the queue
38+
*/
39+
T queuefront() {
40+
// Exercise 1c
41+
return list.getElementAtIndex(0);
42+
}
43+
44+
/**
45+
* Gets the element at the rear of the queue without removing it.
46+
*
47+
* @return the element at the rear of the queue
48+
*/
49+
T queuerear() {
50+
// Exercise 1d
51+
return list.getElementAtIndex(list.getSize() - 1);
52+
// return list.last.element;
53+
}
54+
55+
/**
56+
* Checks if the queue is empty.
57+
*
58+
* @return true if the queue is empty, false otherwise
59+
*/
60+
boolean isEmpty() {
61+
return list.isEmpty();
62+
}
63+
64+
/**
65+
* Creates a copy of this queue.
66+
*
67+
* @return a new queue containing the same elements as this queue
68+
*/
69+
Queue<T> copyQueue() { // Exercise 2
70+
Queue<T> Q2 = new Queue<T>();
71+
// Add your code here
72+
int size = list.size;
73+
for (int i = 0; i < size; i++) {
74+
T element = this.dequeue();
75+
Q2.enqueue(element);
76+
this.enqueue(element);
77+
}
78+
return Q2;
79+
}
80+
81+
/**
82+
* Checks if this queue is identical to another queue in terms of content and
83+
* sequence.
84+
*
85+
* @param Q2 the queue to compare with
86+
* @return true if the queues are identical, false otherwise
87+
*/
88+
boolean isIdentical(Queue<T> Q2) {
89+
// Exercise 3
90+
if (Q2.list.getSize() != this.list.getSize()){
91+
return false;
92+
}
93+
boolean identical = true;
94+
int size = Q2.list.size;
95+
Queue<T> copiedQ1 = this.copyQueue();
96+
Queue<T> copiedQ2 = Q2.copyQueue();
97+
98+
for(int i = 0; i < size; i++){
99+
T removedQ1 = copiedQ1.dequeue();
100+
T removedQ2 = copiedQ2.dequeue();
101+
if (removedQ1 == removedQ2){
102+
copiedQ1.enqueue(removedQ1);
103+
copiedQ2.enqueue(removedQ2);
104+
}
105+
else{
106+
return !identical;
107+
}
108+
}
109+
return identical;
110+
}
111+
112+
/**
113+
* Prints the elements of the queue horizontally. Handles potential
114+
*
115+
*/
116+
void printHorizontal() {
117+
Node<T> walker = list.first;
118+
while (walker != null) {
119+
System.out.print(walker.element + " ");
120+
walker = walker.next;
121+
}
122+
123+
}
124+
125+
}

‎LAB7_BinarySearchTree/src/SList.java

+252
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,252 @@
1+
/**
2+
* The {@code SList} class represents a singly linked list that can hold
3+
* elements of a generic type {@code T}. It provides methods for adding elements
4+
* to the beginning and end of the list, adding elements at a specified index,
5+
* removing elements from the beginning and end of the list, removing elements
6+
* at a specified index, checking if the list is empty, obtaining the size of
7+
* the list, and searching for elements within the list.
8+
*
9+
* @param <T> The type of elements stored in the singly linked list.
10+
*/
11+
public class SList<T> {
12+
/**
13+
* The number of elements currently stored in the singly linked list.
14+
*/
15+
int size;
16+
/**
17+
* The reference to the first node in the singly linked list.
18+
*/
19+
Node<T> first;
20+
/**
21+
* The reference to the last node in the singly linked list.
22+
*/
23+
Node<T> last;
24+
25+
/**
26+
* Constructs an empty singly linked list with size 0.
27+
*/
28+
SList() {
29+
size = 0;
30+
first = null;
31+
last = null;
32+
}
33+
34+
/**
35+
* Adds a new element to the beginning of the singly linked list.
36+
*
37+
* @param element The element to be added to the list.
38+
*/
39+
void addFirst(T element) {
40+
Node<T> newNode = new Node<T>(element);
41+
newNode.next = first; //connect with the previous first
42+
first = newNode; //update first
43+
size++;
44+
if (last == null)
45+
last = first;
46+
}
47+
48+
/**
49+
* Adds a new element to the end of the singly linked list.
50+
*
51+
* @param element The element to be added to the list.
52+
*/
53+
void addLast(T element) {
54+
// Ex.1 complete the method
55+
if (size == 0){
56+
addFirst(element);
57+
}
58+
59+
else if (size > 0){ //if we use 'if' instead of 'else if' it will generate
60+
Node<T> newnode = new Node<T>(element);
61+
last.next = newnode; //connect last with newnode
62+
last = newnode; //update last
63+
size++;
64+
}
65+
}
66+
67+
/**
68+
* Adds a new element at the specified index in the singly linked list. If the
69+
* index is 0, the element is added to the beginning of the list. If the index
70+
* is greater than or equal to the size, the element is added to the end of the
71+
* list.
72+
*
73+
* @param index The index at which to add the element.
74+
* @param element The element to be added to the list.
75+
*/
76+
void addAtIndex(int index, T element) {
77+
// Ex.2 complete the method
78+
if (index <= 0){
79+
addFirst(element); //add at index 0 is equal to addFirst(element)
80+
}
81+
// else if(index < 0){ (optional)
82+
// return;
83+
// }
84+
else if(index >= size){
85+
addLast(element); //add at last index or futher is equal to addLast(element)
86+
}
87+
else {
88+
Node<T> current = first;
89+
for (int i = 0; i < index-1; i++){
90+
current = current.next; //access attributes of the node @i-1
91+
}
92+
Node<T> newnode = new Node<T>(element);
93+
newnode.next = current.next; //connect newnode to the next one
94+
current.next = newnode; //newnode is set to current.next
95+
size++;
96+
}
97+
}
98+
99+
/**
100+
* Removes and returns the first element from the singly linked list.
101+
*
102+
* @return The removed element, or {@code null} if the list is empty.
103+
*/
104+
T removeFirst() {
105+
if (size == 0) { //there's nothing to remove
106+
return null;
107+
} else if (size == 1) {
108+
Node<T> temp = first;
109+
first = null;
110+
last = null; //if there's nothing left after removed, update last = null
111+
size = 0;
112+
return temp.element;
113+
}
114+
else if (size > 1){
115+
Node<T> temp = first; //create temp node
116+
first = first.next; //move first to the next one
117+
size--;
118+
return temp.element;
119+
}
120+
return null;
121+
}
122+
123+
/**
124+
* Removes and returns the last element from the singly linked list.
125+
*
126+
* @return The removed element, or {@code null} if the list is empty.
127+
*/
128+
T removeLast() {
129+
// Ex.3 complete the method
130+
if (size == 0) {
131+
return null;
132+
} else if (size == 1){ //has just only one to remove, need to update first, last = null and size = 0
133+
Node<T> temp = first;
134+
first = null;
135+
last = null;
136+
size = 0;
137+
return temp.element;
138+
} else if (size > 1) {
139+
Node<T> current = first;
140+
for (int i = 0; i < size - 1; i++){ //access attributes of the 2nd last node
141+
current = current.next;
142+
}
143+
//or access attributes of 2nd node by while loop
144+
// while(current.next != last){
145+
// current = current.next;
146+
// }
147+
Node<T> temp = last; //create temp node for removing
148+
last = current; //update last to current (2nd last index)
149+
last.next = null; //unlink with the last node
150+
size--;
151+
return temp.element;
152+
}
153+
return null;
154+
}
155+
156+
/**
157+
* Removes and returns the element at the specified index in the singly linked
158+
* list.
159+
*
160+
* @param index The index of the element to be removed.
161+
* @return The removed element, or {@code null} if the index is out of bounds.
162+
*/
163+
T removeAtIndex(int index) {
164+
// Ex.4 complete the method
165+
if (index <= 0){
166+
return removeFirst();
167+
} else if (index >= size) {
168+
return removeLast();
169+
}
170+
else{
171+
Node<T> current = first;
172+
for(int i = 0; i < index - 1; i++){ //access attributes before the index node)
173+
current = current.next;
174+
}
175+
Node<T> temp = current.next; //create temp node for index to be removed
176+
current.next = temp.next; //connect the previous node with the next node (from temp)
177+
temp.next = null; //break the link of nextnode
178+
size--;
179+
return temp.element;
180+
}
181+
}
182+
183+
/**
184+
* Searches for the first occurrence of a specified item in the singly linked
185+
* list and returns its index.
186+
*
187+
* @param item The item to search for.
188+
* @return The index of the first occurrence of the item, or {@code -1} if not
189+
* found.
190+
*/
191+
int search(T item) {
192+
// Ex.5 complete the method
193+
Node<T> current = first;
194+
int i = 0;
195+
while(i < size && current.element != item){
196+
current = current.next;
197+
i++;
198+
}
199+
if (i <= size - 1) {
200+
// The item was found in the list
201+
return i;
202+
} else {
203+
// The item was not found in the list
204+
return -1;
205+
}
206+
207+
}
208+
209+
/**
210+
* Checks whether the singly linked list is empty.
211+
*
212+
* @return {@code true} if the list is empty, {@code false} otherwise.
213+
*/
214+
boolean isEmpty() {
215+
if (size == 0)
216+
return true;
217+
else
218+
return false;
219+
}
220+
221+
/**
222+
* Returns the current size of the singly linked list.
223+
*
224+
* @return The number of elements in the list.
225+
*/
226+
int getSize() {
227+
228+
return size;
229+
}
230+
T getElementAtIndex(int index){
231+
Node<T> current = first;
232+
for (int i = 0; i < index; i++){
233+
current = current.next;
234+
}
235+
return current.element;
236+
}
237+
238+
/**
239+
* Prints the elements of the singly linked list horizontally, followed by a
240+
* horizontal line separator. This method is primarily used for debugging and
241+
* displaying the contents of the list.
242+
*/
243+
void printHorizontal() {
244+
Node<T> walker = first;
245+
for (int i = 0; i < size; i++) {
246+
System.out.print(walker.element);
247+
System.out.print(" ");
248+
walker = walker.next;
249+
}
250+
System.out.println("\n-----");
251+
}
252+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
/**
2+
* The {@code SListExtension} class provides utility methods for working with singly
3+
* linked lists, specifically for printing the elements vertically.
4+
*/
5+
public class SListExtension {
6+
7+
/**
8+
* Prints the elements of a singly linked list vertically.
9+
*
10+
* @param list The singly linked list to be printed vertically.
11+
* @param <T> The type of elements in the linked list.
12+
*/
13+
public static <T> void printVertical(SList<T> list) {
14+
Node<T> walker = list.first;
15+
while (walker != null) {
16+
System.out.println(walker.element);
17+
walker = walker.next;
18+
}
19+
System.out.println("-----");
20+
}
21+
22+
}

‎LAB7_BinarySearchTree/src/Stack.java

+194
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,194 @@
1+
/**
2+
* The {@code Stack<T>} class represents a generic stack data structure
3+
* implemented using a singly linked list. It provides methods for push, pop,
4+
* peek, copy, printing, binary conversion, and more.
5+
*
6+
* @param <T> The type of elements stored in the stack.
7+
*/
8+
class Stack<T> {
9+
10+
private SList<T> list = new SList<T>();
11+
12+
/**
13+
* Constructs an empty stack.
14+
*/
15+
Stack() {
16+
}
17+
18+
/**
19+
* Pushes an element onto the top of the stack.
20+
*
21+
* @param element The element to be pushed onto the stack.
22+
*/
23+
void push(T element) {// Exercise 1a
24+
list.addFirst(element);
25+
}
26+
27+
/**
28+
* Removes and returns the element at the top of the stack.
29+
*
30+
* @return The element removed from the top of the stack.
31+
*/
32+
T pop() {// Exercise 1b
33+
34+
//T tmp =
35+
return list.removeFirst();
36+
// return null;
37+
}
38+
39+
/**
40+
* Retrieves the element at the top of the stack without removing it.
41+
*
42+
* @return The element at the top of the stack.
43+
*/
44+
T peek() {// Exercise 1c
45+
// return list.getElementAtIndex(list.getSize() - 1);
46+
return list.first.element;
47+
// return null;
48+
}
49+
50+
/**
51+
* Checks if the stack is empty.
52+
*
53+
* @return {@code true} if the stack is empty, {@code false} otherwise.
54+
*/
55+
boolean isEmpty() {
56+
57+
return list.isEmpty();
58+
}
59+
60+
/**
61+
* Creates and returns a copy of the stack.
62+
*
63+
* @return A copy of the stack.
64+
*/
65+
Stack<T> copyStack() {
66+
Stack<T> rvStack = reverseStack();
67+
return rvStack.reverseStack();
68+
}
69+
70+
/**
71+
* Prints the elements of the stack vertically.
72+
*/
73+
void printVertical() {
74+
SListExtension.printVertical(list);
75+
}
76+
77+
/**
78+
* Converts an integer to binary representation and prints it.
79+
*
80+
* @param x The integer to be converted to binary.
81+
*/
82+
static void binaryConversion(int x) {// Exercise 2
83+
Stack<Integer> answer = new Stack<Integer>();
84+
// Write your code here
85+
if (x == 0){ //case num = 0
86+
answer.push(0);
87+
}
88+
while (x > 0) {
89+
answer.push(x%2);
90+
x /= 2;
91+
}
92+
answer.printVertical();
93+
}
94+
95+
/**
96+
* Reverses the order of elements in the stack.
97+
*
98+
* @return A new stack with the reversed order of elements.
99+
*/
100+
Stack<T> reverseStack() {// Exercise 3
101+
Stack<T> S2 = new Stack<T>();
102+
Stack<T> temp = new Stack<T>();
103+
104+
while (!this.isEmpty()) {
105+
T e = this.pop(); //ori is just a variable name
106+
S2.push(e); //push into reversedStack
107+
temp.push(e); //push into temp stack
108+
}
109+
while (!temp.isEmpty()) { //to generate back original stack
110+
T e = temp.pop();
111+
// System.out.println(e);
112+
this.push(e);
113+
// push(temp.pop());
114+
//pop from temp stack and push into a stack (to generate back original stack)
115+
}
116+
return S2;
117+
}
118+
119+
/**
120+
* Checks if a given string is a palindrome (case-insensitive).
121+
*
122+
* @param word The string to be checked for palindrome.
123+
* @return {@code true} if the string is a palindrome, {@code false} otherwise.
124+
*/
125+
static boolean isPalindrome(String word) {// Exercise 4
126+
Stack<Character> S1 = new Stack<Character>();
127+
for (int i = 0; i < word.length(); i++){
128+
S1.push(word.charAt(i));
129+
}
130+
Stack<Character> S2 = S1.reverseStack();
131+
while (!S1.isEmpty()){
132+
if (S1.pop() != S2.pop()){
133+
return false;
134+
}
135+
}
136+
return true;
137+
}
138+
139+
/**
140+
* Checks if a string represents an integer.
141+
*
142+
* @param s The string to be checked.
143+
* @return {@code true} if the string represents an integer, {@code false}
144+
* otherwise.
145+
*/
146+
public static boolean isInteger(String s) {
147+
try {
148+
Integer.parseInt(s);
149+
} catch (NumberFormatException nfe) {
150+
return false;
151+
}
152+
return true;
153+
}
154+
155+
/**
156+
* Evaluates a postfix expression and returns the result.
157+
*
158+
* @param input The postfix expression as an array of strings.
159+
* @return The result of evaluating the postfix expression.
160+
*/
161+
public static Integer evalPostfix(String[] input) {// Exercise 5
162+
Stack<Integer> S = new Stack<Integer>();
163+
// Write your code here
164+
for (int i = 0; i < input.length; i++){
165+
if (isInteger(input[i])){
166+
S.push(Integer.parseInt(input[i])); //to parse String to int
167+
}
168+
else if(input[i] == "+"){
169+
S.push(S.pop() + S.pop());
170+
}
171+
else if (input[i] == "-"){
172+
S.push(-1*(S.pop() - S.pop()));
173+
174+
}
175+
else if (input[i] == "*"){
176+
S.push(S.pop()* S.pop());
177+
}
178+
else if (input[i] == "/"){
179+
int divider = S.pop();
180+
int dividend = S.pop();
181+
S.push(dividend/divider);
182+
183+
}
184+
else if (input[i] == "%"){
185+
int divider = S.pop();
186+
int dividend = S.pop();
187+
S.push(dividend%divider);
188+
189+
}
190+
191+
}
192+
return S.peek();
193+
}
194+
}
+100
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,100 @@
1+
2+
public class TestBST {
3+
public static void main(String[] args) {
4+
BST<Integer> bst = new BST<Integer>();
5+
6+
// Ex1. Uncomment below to test insert() //////////////////////////////
7+
System.out.println("Testing insert()...");
8+
bst.insert(8);
9+
bst.insert(19);
10+
bst.insert(3);
11+
bst.insert(9);
12+
bst.insert(5);
13+
bst.insert(1);
14+
bst.insert(15);
15+
System.out.print("BFT of your BST is ");
16+
bst.PrintBFT();
17+
System.out.println("\nThe correct answer is 8 3 19 1 5 9 15\n\n");
18+
19+
System.out.print("Preorder of your BST is ");
20+
bst.preorder();
21+
System.out.println("\nThe correct answer is 8 3 1 5 19 9 15\n\n");
22+
23+
System.out.print("Inorder of your BST is ");
24+
bst.inorder();
25+
System.out.println("\nThe correct answer is 1 3 5 8 9 15 19\n\n");
26+
27+
System.out.print("Postorder of your BST is ");
28+
bst.postorder();
29+
System.out.println("\nThe correct answer is 1 5 3 15 9 19 8\n\n");
30+
System.out.println("Height of your BST = " + bst.findHeight());
31+
System.out.println("The correct answer is 4");
32+
33+
// Ex2. Uncomment below to test delete() //////////////////////////////
34+
/*System.out.println("\nTesting delete()...");
35+
36+
if (bst.delete(2) == null) {
37+
System.out.println("bst.delete(2) is null");
38+
}
39+
System.out.println("The correct answer is null\n");
40+
41+
bst.delete(1);
42+
System.out.print("BFT of your BST is ");
43+
bst.PrintBFT();
44+
System.out.println("\nThe correct answer is 8 3 19 5 9 15\n");
45+
46+
bst.delete(19);
47+
System.out.print("BFT of your BST is ");
48+
bst.PrintBFT();
49+
System.out.println("\nThe correct answer is 8 3 9 5 15\n");
50+
51+
bst.delete(8);
52+
System.out.print("BFT of your BST is ");
53+
bst.PrintBFT();
54+
System.out.println("\nThe correct answer is 5 3 9 15\n");
55+
56+
bst.delete(3);
57+
System.out.print("BFT of your BST is ");
58+
bst.PrintBFT();
59+
System.out.println("\nThe correct answer is 5 9 15\n");
60+
61+
bst.delete(5);
62+
System.out.print("BFT of your BST is ");
63+
bst.PrintBFT();
64+
System.out.println("\nThe correct answer is 9 15\n");
65+
66+
System.out.println("Height of your BST = " + bst.findHeight());
67+
System.out.println("The correct answer is 2");*/
68+
69+
// Ex3. Uncomment below to test search() //////////////////////////////
70+
/*System.out.println("\nTesting search()...");
71+
if (bst.search(12)) {
72+
System.out.println("12 is found");
73+
} else {
74+
System.out.println("12 is not found");
75+
}
76+
System.out.println("The correct answer is 12 is not found\n");
77+
78+
if (bst.search(15)) {
79+
System.out.println("15 is found");
80+
} else {
81+
System.out.println("15 is not found");
82+
}
83+
System.out.println("The correct answer is 15 is found\n");*/
84+
85+
// Ex4. Uncomment below to test findSmallest() //////////////////////////////
86+
/*bst.insert(1);
87+
bst.insert(3);
88+
bst.insert(19);
89+
System.out.println("\nTesting findSmallest()...");
90+
System.out.println("The smallest element is " + bst.findSmallest(bst.root).element);
91+
System.out.println("The correct answer is 1\n");*/
92+
93+
// Ex5. Uncomment below to test findLargest() //////////////////////////////
94+
/*System.out.println("\nTesting findLargest()...");
95+
System.out.println("The largest element is " + bst.findLargest(bst.root).element);
96+
System.out.println("The correct answer is 19");*/
97+
98+
}
99+
100+
}

0 commit comments

Comments
 (0)
Please sign in to comment.