Tree
Tree
TREE
Dr
Mourad Raafat
Definition
v is a descendant of a node u if u is an
ancestor of v.
pr3 is a descendant of cs016/.
Full or proper BT
strictly has zero or two children
Complete BT
every level complete
May be complete left side
Perfect BT
All nodes have two children except leaves also same level
A binary tree representing an arithmetic expression. This tree represents the expression ((((3 +1)×3)/((9
−5)+2))−((3×(7−4)) +6)). The value associated with the internal node labeled “/” is 2.
Motivation for BT
1- If we have to represent the data in a linked structure, i.e., linked list, (because we
cannot anticipate the maximum number of elements), while keeping the search fast.
Notice that: this idea is immediate after our analysis to the binary search in arrays.
2- Building Expression Trees (has great importance in syntactical analysis and parsing),
along with the validity of expressions
+ log !
a b b n
a+b log b n!
a
b c
a+bc 12
Before ADT and coding, How to traverse a BT? More motivations and benefits
There was no problem for traversing a linear structure like a list. For a BT, at each node
V having left and right subtrees L and R (respectively) we can do the following visiting:
The standards are Pre, In, and Post order. In the three of them, L precedes R; then V is
before them (Pre) or in between (In) or after them (Post).
Example: +
The Polish Forms (Ch 12) are
Preorder: +ab related to these orders.
Inorder: a+b b Preorder Prefix
a
Postorder: ab+ Inorder Infix
a+b Postorder Postfix
+
Example:
Also notice the strong
Preorder: +abc
a connection between these
Inorder: a+bc traversal modes on a hand
Postorder: abc+ and recursion and stacks on
b c
the other hand. 13
a+bc
Before ADT and coding, How to traverse a BT? More motivations and benefits
Notice that:
For a BT produced by binary search, the Inorder traversal produces sorted elements.
5
2 8
1 3 6 9
F F F 4 F 7 F 10
F F F F F F
1 2 3 4 5 6 7 8 9 10
Now, we have enough motivation for having BTs as data structures. Let us define
the ADT and start coding as linked implementation.
14
Definition: A Binary Tree ADT is either empty, or it consists of a node (vertex)
called the root together with two binary trees called the left subtree and the right
subtree of the root. This is together with the following operations:
We will define the next operations for a special type of BT, i.e., Binary Search
Trees (which will be defined later).
7. Insert a new entry (we have to define where)
8. Delete an entry (we have to define from where)
9. Search for an element.
10. (Any other operation to be defined later).
15