03 - APS - Tree
03 - APS - Tree
Tree
Damjan Strnad
2
height=4 2
4
6
J K L
7
Binary tree
●
a binary tree is a tree in which nodes have at most
degree 2
●
a binary tree with no nodes is an empty tree or a null
tree. We denote it with NIL.
●
every node in a binary tree has a left subtree and a right
subtree which can be empty root
left right
●
if the left subtree is not empty subtree subtree
Binary tree
●
in a full binary tree each node has 0 or 2
children
depth
●
in a perfect or complete binary 0
tree all inner nodes have two 1
children and all leaves are on the height=3
2
same depth 3
●
a special case of balanced binary tree is an
aligned binary tree, in which each level,
except perhaps the last one, has maximum
number of nodes
9
●
iterative implementation:
ITERATIVE-TREE-SEARCH(x,k)
while x ≠ NIL and k ≠ key[x] do
if k < key[x] then
x ← leftChild[x] % move to left subtree
else
x ← rightChild[x] % move to right subtree
return x
15
2 3
6 18
4 5 6 7
3 7 17 20
8 9 10
2 4 13
11
9
16
4 5 6 7
3 7 17 20
8 9 10
2 4 13
11
9
2 3
6 18
17<18
4 5 6 7
3 7 17 20
8 9 10
2 4 13
11
9
2 3
6 18
4 5 6 7
3 7 17 20
17=17
8 9 10
2 4 13
11
9
2 3
6 18
4 5 6 7
3 7 17 20
8 9 10
2 4 13
11
9
20
4 5 6 7
3 7 17 20
8 9 10
2 4 13
11
9
2 3
6 18
8>6
4 5 6 7
3 7 17 20
8 9 10
2 4 13
11
9
2 3
6 18
4 5 6 7
3 7 17 20
8>7
8 9 10
2 4 13
11
9
2 3
6 18
4 5 6 7
3 7 17 20
8 9 10
2 4 13
8<13
11
9
2 3
6 18
4 5 6 7
3 7 17 20
8 9 10
2 4 13
8<13
11
9
NIL
2 3
6 18
4 5 6 7
3 7 17 20
8 9 10
2 4 13
8<13
11
9
NIL
4 5 6 7
3 7 17 20
8 9 10
2 4 13
11
9
27
4 5 6 7
3 7 17 20
8 9 10
2 4 13
11
9
28
(key value 4) 4 5 6 7
3 7 17 20
– successor of node 10 8 9 10
1
15
2 3
6 18
4 5 6 7
3 7 17 20
8 9 10
2 4 13
11
9
32
2 3
6 18
4 5 6 7
3 7 17 20
8 9 10
2 4 13
11
9
33
2 3
6 18
4 5 6 7
3 7 17 20
8 9 10
2 4 13
11
9
34
●
example: insert key 16 into existing tree T
1
15 1
15
2 3
26 18 3
6 19
4 5 6 7
3 7 17 20
4 5 6 7
3 7 17
8 20
13
8
18
36
●
example: insert key 16 into existing tree T
1
15 1
15
2 3
26 18 3
6 19
4 5 6 7
3 7 17 20
4 5 6 7
3 7 17
8 20
13
8
18
37
●
example: insert key 16 into existing tree T
1
15 1
15
2 3
26 18 3
6 19
4 5 6 7
3 7 17 20
4 5 6 7
3 7 17
8 20
13
z 8
16 18
38
15 15
6 19 6 19
z
3 7 17 20 3 17 20
16 18 16 18
40
15 15
z
6 18 6 22
3 7 22 3 7 20
20
41
3 7 17 20
2 4 13
9
42
3 7 17 20
2 4 13
9
43
3 7 17 20
2 13
9
44
3 7 17 20
2 4 13
9
45
3 7 17 20
2 4 13
9
46
3 7 17 20
2 4 13
9
47
3 13 17 20
2 4 9