This commit is contained in:
louiscklaw
2025-01-31 19:15:17 +08:00
parent 09adae8c8e
commit 6c60a73f30
1546 changed files with 286918 additions and 0 deletions

View File

@@ -0,0 +1,32 @@
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class BstTiming {
public static void main(String[] args) {
try {
StringBst tree = new StringBst();
Scanner fin = new Scanner(new File(args[0]));
String line;
while (fin.hasNextLine()) {
line = fin.nextLine();
line = line.trim();
tree.addNode(line);
}
fin.close();
long startTime = System.nanoTime();
String ans = tree.search(args[1]);
long endTime = System.nanoTime();
if (ans==null)
System.out.println("Not found; Time used: " + (endTime - startTime));
else
System.out.println("Found; Time used: " + (endTime - startTime));
}
catch (FileNotFoundException e) {
System.out.println("Failed to open " + args[0]);
}
catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Usage: BstTiming <word_file> <search_word>");
}
}
}

View File

@@ -0,0 +1,240 @@
### Q2(c)
Now, perform some experiments to test the searching performance in the two approaches. Record the results in the table below. You are free to try some more words.
| Word to search for | Result (found/ not found) | Time needed (BST) | Time needed (linked list)
| --- | --- | --- | --- |
| water | Found | 2500 | 7100 |
| ever | Found | 4800 | 77600 |
| snail | Not Found | 4500 | 74200 |
| better | Not Found | 3900 | 80700 |
| apple | Found | 5700 | 49700 |
| door | Found | 3300 | 7300 |
| foolish | Found | 4000 | 52000 |
### Q4
A proper binary tree contains N nodes. What is the number of leaf nodes in the tree? What is the
number of non-leaf nodes in the tree?
```
Leaf nodes = N/2+1 (N must be an odd number, so take the integer of N/2.)
Non-leaf nodes = N/2
```
### Q5
A complete binary tree has a depth of 8. What is the total number of nodes in the tree? Give the
relationship of the depth and the total number of nodes of a complete binary tree in a mathematic
expression.
```
Total nodes = 2^(8+1) 1 = 511
```
### Q6a
Draw the array of the binary tree if it is implemented in an
array.
```
[Q]
/ \
[B] [U]
\ / \
[G] [R][W]
/ \
[E] [J]
\ / \
[F] [I] [P]
/
[H]
```
```
0:Q 1:B 2:U 4:G 5:R 6:W 9:E 10:J 20:F 21:I 22:P 43:H
```
### Q6(b)
(b)List the node sequence by
(i) pre-order traversal
```
Q B G E F J I H P U R W
```
(ii) in-order traversal
```
B E F G H I J P Q R U W
```
(iii) post-order traversal
```
F E H I P J G B R W U Q
```
### Q7
Follow the algorithm outlined in the lecture notes, depict the Binary Search Trees created by inserting the items below from left to right. Perform an in-order traversal to check if the nodes are visited in ascending order.
(a) M J W S G L K A B P Z X Y R T
```
M
/ \
/ \
/ \
/ \
J W
/ \ / \
G L / \
/ / / \
A K S Z
\ / \ /
B / \ X
P T \
\ Y
R
```
(b) P W J Y B L S G K M A Z X T R
```
P
/ \
/ \
/ \
/ \
/ \
/ \
/ \
/ \
J W
/ \ / \
/ \ / \
/ \ / \
B L / \
/ \ / \ S Y
A G / \ / \ / \
K M / \ / \
R T X Z
```
(c) P W J Y B L S G K M A R
```
P
/ \
/ \
/ \
/ \
/ \
J W
/ \ / \
/ \ S Y
/ \ /
B L R
/ \ / \
A G / \
K M
```
(d) P W J Y B L S G K M A
```
P
/ \
/ \
/ \
/ \
/ \
J W
/ \ / \
/ \ S Y
/ \
B L
/ \ / \
A G / \
K M
```
(e) A B C D E F G H I J K L
```
A
\
B
\
C
\
D
\
E
\
F
\
G
\
H
\
I
\
J
\
K
\
L
```
(f) L K J I H G F E D C B A
```
L
/
K
/
J
/
I
/
H
/
G
/
F
/
E
/
D
/
C
/
B
/
A
```
### Q8
Outline an algorithm of searching an item in a Binary Search Tree.
```
BinaryNode search (BinaryNode t, key x)
begin
if t is null
return null;
if (x is less than t.data.key)
return search(t.left, x);
else if (x is greater than t.data.key)
return search(t.right, x);
else
return t;
end
```
### Q10
Give the postfix and prefix expressions as well as the expression tree.
((A + B) * C) / (D + E) * F
```
[*]
/ \
[/] [F]
/ \
/ \
/ \
[*] [+]
/ \ / \
[+] [C] [D] [E]
/ \
/ \
[A] [B]
pre-order traversal on the expression tree to yields the prefix expression
Prefix expression: * / * + A B C + D E F
```

View File

@@ -0,0 +1,89 @@
public class StringBst {
private StringBstNode root;
public StringBst() {
root = null;
}
public void addNode(String data) {
StringBstNode p = root, prev = null;
if (root == null) {
root = new StringBstNode(data);
return;
}
while (p != null) {
prev = p;
if (data.compareTo(p.getData()) < 0) {
p = p.getLeft();
} else {
p = p.getRight();
}
}
if (data.compareTo(prev.getData()) < 0) {
prev.setLeft(new StringBstNode(data));
} else {
prev.setRight(new StringBstNode(data));
}
}
public String search(String data) {
StringBstNode p = root;
if (root == null) {
return null;
}
while (p!=null) {
if (data.compareTo(p.getData()) < 0) {
p = p.getLeft();
} else if(data.compareTo(p.getData()) > 0){
p = p.getRight();
}
else{
return p.getData();
}
}
return null;
}
public void preorder() {
preorder(root);
}
public void preorder(StringBstNode v) {
System.out.print(v.getData() + " ");
if (v.getLeft() != null) {
preorder(v.getLeft());
}
if (v.getRight() != null) {
preorder(v.getRight());
}
}
public void inorder() {
inorder(root);
}
public void inorder(StringBstNode v) {
if (v.getLeft() != null) {
inorder(v.getLeft());
}
System.out.print(v.getData() + " ");
if (v.getRight() != null) {
inorder(v.getRight());
}
}
public void postorder() {
postorder(root);
}
public void postorder(StringBstNode v) {
if (v.getLeft() != null) {
postorder(v.getLeft());
}
if (v.getRight() != null) {
postorder(v.getRight());
}
System.out.print(v.getData() + " ");
}
}

View File

@@ -0,0 +1,32 @@
public class StringBstNode {
private String data;
private StringBstNode left;
private StringBstNode right;
public StringBstNode(String data) {
this.data = data;
this.left = null;
this.right = null;
}
public String getData() {
return data;
}
public StringBstNode getLeft() {
return left;
}
public StringBstNode getRight() {
return right;
}
public void setLeft(StringBstNode p) {
left = p;
}
public void setRight(StringBstNode p){
right =p;
}
}

View File

@@ -0,0 +1,853 @@
water
button
door
able
circle
near
comfort
sock
open
only
road
addition
plough
science
level
expansion
ear
education
insurance
shake
fixed
bone
card
laugh
winter
burst
answer
physical
sense
get
clear
thumb
island
eye
ornament
gold
again
old
point
purpose
plate
distance
drop
daughter
VTC
range
silk
rain
brown
interest
business
skin
condition
danger
paste
boy
adjustment
polish
time
net
jump
fight
stomach
talk
white
animal
neck
no
garden
list
star
drink
chest
tin
feeble
direction
and
land
warm
than
digestion
manager
match
mixed
moon
quiet
tray
jelly
transport
chin
wait
hand
opinion
use
join
cook
potato
cloud
heart
debt
stop
snake
complex
fowl
mind
month
arch
growth
care
plane
argument
about
say
because
ship
colour
responsible
elastic
flag
error
front
hear
wax
ray
coal
unit
suggestion
well
news
trousers
surprise
prison
bread
beautiful
death
wound
harmony
mine
river
opposite
off
this
ant
history
cough
watch
observation
move
not
balance
cry
relation
pull
if
clean
cover
breath
weather
comb
that
trouble
smash
root
voice
sail
disease
important
cup
look
belief
give
hate
over
forward
basket
soap
before
oven
coat
have
exchange
berry
branch
brick
umbrella
political
crack
in
goat
he
bad
dust
far
night
word
structure
mist
the
violent
stretch
keep
pot
rhythm
across
necessary
pen
other
sharp
middle
cushion
brush
cloth
reaction
chief
military
late
electric
brass
ball
married
roll
dress
under
plant
awake
camera
need
quick
knee
great
example
wing
property
seat
shoe
smoke
equal
fold
boat
sudden
wrong
start
fat
shelf
servant
past
safe
tail
cake
to
low
simple
rod
attraction
stick
trick
natural
why
rub
church
bell
you
secret
wave
humour
loud
step
disgust
canvas
idea
insect
mother
boiling
by
mark
fish
west
wine
dog
butter
where
gun
ring
bee
wool
end
basin
stem
verse
company
nail
cotton
account
who
bulb
slow
taste
note
engine
amusement
spring
face
conscious
female
go
slope
play
wood
north
drain
automatic
finger
roof
school
FALSE
loss
sound
form
new
rate
father
cord
place
pig
behaviour
material
peace
committee
board
attack
shade
see
sex
needle
but
table
hour
year
porter
salt
with
oil
flight
bed
seed
money
sweet
rule
fact
black
against
for
baby
loose
quite
support
learning
edge
tax
writing
waste
decision
damage
make
down
sand
man
sticky
wall
then
love
will
doubt
pipe
shame
little
grip
still
tree
body
pocket
left
let
morning
earth
through
pin
copper
picture
leather
representative
field
birth
egg
limit
print
thin
fiction
control
walk
discussion
payment
sleep
song
cheap
knowledge
sea
public
present
as
steam
angry
army
fire
milk
discovery
after
future
sneeze
strong
trade
question
fork
vessel
room
rough
horse
reward
slip
work
deep
nation
linen
from
rice
east
grey
while
order
blow
south
so
process
week
dry
sister
price
tendency
back
blood
jewel
I
stiff
chemical
substance
seem
group
whistle
hair
experience
bird
push
yesterday
knife
how
may
wide
general
thick
secretary
foot
certain
hammer
band
expert
hanging
bottle
attention
motion
prose
development
stage
head
cheese
effect
brother
wind
credit
language
shock
at
produce
cow
out
up
sad
bit
high
nose
complete
law
almost
music
metal
arm
frame
round
degree
sign
apple
bridge
twist
steel
self
line
noise
pencil
knot
be
small
send
snow
ice
copy
detail
bitter
chance
space
muscle
dear
put
special
top
poor
soup
industry
rest
stamp
part
destruction
a
bucket
tight
dark
bent
hospital
rail
hollow
stitch
office
competition
house
pleasure
religion
change
soft
punishment
ready
heat
page
turn
chain
train
spoon
design
tomorrow
advertisement
probable
fear
act
summer
toe
increase
yes
full
throat
much
when
woman
judge
memory
floor
different
cork
tired
liquid
kick
sugar
shut
impulse
scale
view
foolish
air
like
whip
pump
tooth
existence
name
brake
key
flower
letter
cat
tall
hearing
lead
strange
smooth
silver
cruel
nut
town
selection
test
first
base
wire
boot
tongue
enough
girl
acid
authority
spade
grain
light
broken
regret
fly
young
help
every
normal
fall
parallel
orange
leg
curve
lock
please
harbour
measure
mass
building
angle
smell
early
powder
blade
profit
street
crime
cold
paper
cart
government
record
sort
force
driving
of
lift
pain
bag
take
now
such
or
hard
meal
long
weight
flame
regular
red
common
parcel
collar
clock
meat
some
blue
fertile
cause
statement
market
scissors
thought
color
theory
value
sky
dependent
poison
comparison
green
window
among
division
station
store
wise
feather
right
art
hole
system
size
map
screw
kiss
ink
run
carriage
invention
desire
current
library
event
chalk
ticket
agreement
horn
reading
between
hook
brain
flat
protest
monkey
come
even
true
short
organization
number
power
male
operation
journey
distribution
reason
minute
story
sponge
worm
thread
apparatus
stone
frequent
friend
wet
family
sun
bath
grass
lip
iron
wash
living
machine
hat
kind
any
good
side
war
mountain
glass
quality
separate
instrument
country
together
curtain
free
approval
day
way
request
society
attempt
waiting
receipt
cup
medical
swim
all
yellow
offer
glove
person
shirt
delicate
square
feeling
teaching
narrow
drawer
paint
position
dead
meeting
solid
same
healthy
serious
last
very
owner
there
burn
private
food
touch
straight
book
son
ill
kettle
skirt
on
fruit
stocking
box
thunder
happy
guide
leaf
respect
nerve
smile
second
bright
possible
do
rat
mouth
bite
sheep
thing
farm
connection
hope
till
crush
dirty
amount
wheel
ever