Trees
•Atreeisacollectionofnodes
–Thecollectioncanbeempty
–Ifnotempty,atreeconsistsofadistinguished
noder(theroot),andzeroormorenonempty
subtreesT
1,T
2,....,T
k,eachofwhoserootsare
connectedbyadirectededgefromr.
Terminologies
•Parent
–Immediate predecessor of a node
•Child
–Immediate successors of a node (left child,right
child)
•Leaves
–Leaves are nodes with no children
•Sibling
–nodes with same parent
Inorder Traversal
•Inorder traversal
–left, root, right
–infix expression
a+b*c+d*e+f*g
Convert a Generic Tree to a Binary Tree
Binary Search Trees
•Binary search tree
–Every node has a unique key.
–The keys in a nonempty left subtreeare smaller
than the key in the root .
–The keys in a nonempty right subtreeare
greaterthan the key in the root .
–The left and right subtrees are also binary
search trees.
BST –Representation
•Represented by a linked data structure of nodes.
•root(T)points to the root of tree T.
•Each node contains fields:
–key
–left–pointer to left child: root of left subtree.
–right–pointer to right child : root of right subtree.
–p–pointer to parent. p[root[T]] = NIL (optional).
Binary Search Tree Property
•Stored keys must satisfy
the binary search tree
property.
–yin left subtree of
x, then key[y]
key[x].
–yin right subtree
of x, then key[y]
key[x].
56
26 200
18 28 190 213
12 2427
Binary Search Trees
A binary search tree
Not a binary search tree
Binary Search Trees
•Average depthof a node is O(log N)
•Maximum depthof a node is O(N)
The same set of keys may have different BSTs
Querying a Binary Search Tree
•Pseudocode
–ifthetreeisempty
returnNULL
–elseiftheiteminthenodeequalsthetarget
returnthenodevalue
–elseiftheiteminthenodeisgreaterthanthe
target
returntheresultofsearchingtheleftsubtree
–elseiftheiteminthenodeissmallerthanthe
target
returntheresultofsearchingtherightsubtree
Iterative Tree Search
Iterative-Tree-Search(x, k)
1. whilex NILandk key[x]
2. doifk <key[x]
3. thenx left[x]
4. elsex right[x]
5. returnx
The iterative tree search is more efficient on most computers.
The recursive tree search is more straightforward.
56
26 200
18 28190 213
122427
Querying a Binary Search Tree
•Alldynamic-setsearchoperationscanbesupportedin
O(h)time.
•h=(lgn)forabalancedbinarytree(andforan
averagetreebuiltbyaddingnodesinrandomorder.)
•h=(n)foranunbalancedtreethatresemblesa
linearchainofnnodesintheworstcase.
Finding Min & Max
Tree-Minimum(x) Tree-Maximum(x)
1. whileleft[x]NIL 1. whileright[x]NIL
2. dox left[x] 2. dox right[x]
3. returnx 3. returnx
The binary-search-tree property guarantees that:
»The minimumis located at the left-mostnode.
»The maximumis located at the right-mostnode.
Predecessor and Successor
•Successorofnodexisthenodeysuchthatkey[y]isthe
smallestkeygreaterthankey[x].
•ThesuccessorofthelargestkeyisNIL.
•Twocases:
–Ifnodexhasanon-emptyrightsubtree,thenx’ssuccessoris
theminimumintherightsubtreeofx.
–Ifnodexhasanemptyrightsubtree,then:
•Aslongaswemovetotheleftupthetree(moveup
throughrightchildren),wearevisitingsmallerkeys.
•x’ssuccessoryisthenodethatxisthepredecessorof(xis
themaximuminy’sleftsubtree).
•Inotherwords,x’ssuccessory,isthelowestancestorofx
whoseleftchildisalsoanancestorofx.
Pseudo-code for Successor
Tree-Successor(x)
1. if right[x]NIL
2. thenreturn Tree-Minimum(right[x])
3. yp[x]
4. whiley NIL andx = right[y]
5. dox y
6. yp[y]
7. returny
Code for predecessor is symmetric.
Running time:O(h)
56
26 200
18 28190 213
12 2427
27
Predecessor
Def:predecessor(x ) =y, such that key [y]is the
biggest key < key [x]
E.g.:predecessor (15) =
predecessor (9) =
predecessor (7) =
Case 1: left (x)is non empty
predecessor(x) = the maximum in left (x)
Case 2: left (x)is empty
go up the tree until the current node is a right child:
predecessor(x ) is the parent of the current node
if you cannot go further (and you reached the root):
xis the smallest element
3
2 4
6
7
13
15
18
17 20
9
13
7
6
x
y
9
7
5
4 68
Case 1:The Tree is Empty
Set the root to a new node containing the item
Case 2:The Tree is Not Empty
Call a recursive helper method to insert the item
10
10 > 7
10 > 9
10
BST Insertion
Analysis of Insertion
•Initialization:O(1)
•While loop in lines 3-7
searches for place to
insert z, maintaining
parent y.
This takes O(h) time.
•Lines 8-13 insert the
value: O(1)
TOTAL: O(h) time to
insert a node.
Tree-Insert(T, z)
1.yNIL
2.x root[T]
3.whilexNIL
4. doy x
5. ifkey[z] < key[x]
6. then x left[x]
7. else x right[x]
8.p[z] y
9.if y = NIL
10. then root[t] z
11. else if key[z] < key[y]
12. then left[y] z
13. else right[y] z
9
7
5
64 8 10
9
7
5
68 10
Case 1:removing a node with 2 EMPTY SUBTREES
parent
cursor
BST Deletion
Removing 4
replace the link in the
parent with null
Case 2:removing a node with 2 SUBTREES
9
7
5
68 10
9
6
5
8 10
cursor
cursor
-replace the node's value with the max value in the
left subtree
-delete the max node in the left subtree
44
Removing
7
BST Deletion
9
7
5
68 10
9
7
5
68 10
cursor
cursor
parent
parent
-the node has no left child:
-link the parent of the node
to the right (non-empty) subtree
Case 3:removing a node with 1 EMPTY SUBTREE
BST Deletion
9
7
5
8 10
9
7
5
8 10
cursor
cursor
parent
parent
-the node has no right child:
-link the parent of the node to the
left (non-empty) subtree
Case 4:removing a node with 1 EMPTY SUBTREE
Removing 5
4 4
BST Deletion
Deletion –Pseudocode
TREE-DELETE(T, z)
1.if left[z]= NIL or right[z]= NIL
2.then y ←z
3.else y ← TREE-SUCCESSOR(z)
4.if left[y]NIL
5.then x ←left[y]
6.else x ←right[y]
7.if x NIL
8.then p[x] ←p[y]
z has one child
z has 2 children
15
16
20
18 23
6
5
123
7
10 13
y
x
Deletion –Pseudocode
TREE-DELETE(T, z)
9.if p[y] = NIL
10.then root[T] ← x
11.else if y = left[p[y]]
12. then left[p[y]] ← x
13. else right[p[y]] ← x
14.if y z
15.then key[z] ← key[y]
16. copy y’s satellite data into z
17.return y
15
16
20
18 23
6
5
123
7
10 13
y
x
Running time: O(h)