Slot12 13 Trees Part2 BinaryTrees
Slot12 13 Trees Part2 BinaryTrees
Natural orders:
On numbers: numerical comparison
On characters, strings: Dictionary order ASCII
comparison
Searching operation will not need to traverse all nodes but a path will be
chosen ( searching x= 7)
Complexity of these operations are improved.
A BST is recommended to use when managing a collection of items in which search
operations are frequently used Search operation must be improved All elements
are stored in pre-defined order.
class BST {
BinTreeNode root = null;
}
Balanced BST of
Integers
BST of Integers
Program
User
Interface:
12
Trees, Part 2: BST Trees
Algorithms on BSTs
Managing, Initializing
Add new node
Get minimum, maximum values
Calculate tree’s height
Traverse
Search
Delete
Add a
new node
We can
find the
The IntBstTree class
tree’s
height
using a
traversal
only
Traversal Algorithms:
1 3 6 9
From each
linked-list
result of each
traversal,
create an
iterator, an
object for
processing
nodes, one-by-
one at a time.
father
delNode x
delNode = root
x x
grandFather
GF
delNode
x
GC
grandChild
Trees, Part 2: BST Trees 27
Alg.: Deleting
Removing a 2-child node by Merging The IntBstTree class
delNode
grandFather
leftGrandChild rightGrandChild
rightMost
The tree’s height
may increase
(this example)
rightMost
Removing
a 2-child
node by
Merging
Exercise: (1) After the node 1 was deleted, what is father of the node 0?
Remove (2) After the node 4 was deleted, what is child of the node 3?
(3) After the node 5 was deleted what is father of the node 4?
nodes by (4) After the node 14 was deleted, what is father of the node 18?
merging (5) After the node 9 was deleted, what is the tree’s height?
Exercise: (1) After the node 9 was deleted, what is father of the node 2?
Remove (2) After the node 9 was deleted, what is child of the node 14?
(3) After the node 6 was deleted what is father of the node 5?
nodes by (4) After the node 11 was deleted, what is father of the node 10?
merging (5) After the node 9 was deleted, what is the tree’s height?
Advantage
The tree’s height is preserved or
may be reduced because a path
reduces one in it’s length.
Public method
Exercise:
Remove (1) After the node 1 was deleted, what is father of the node 0?
nodes by (2) After the node 4 was deleted, what is child of the node 3?
(3) After the node 5 was deleted what is father of the node 4?
copying (4) After the node 14 was deleted, what is father of the node 18?
Exercise: (1) After the node 9 was deleted, what is father of the node 2?
Remove (2) After the node 9 was deleted, what is child of the node 14?
(3) After the node 6 was deleted what is father of the node 5?
nodes by (4) After the node 11 was deleted, what is father of the node 10?
copying (5) After the node 11 was deleted, what is the tree’s height?