Binary Trees
Binary Trees
Binary trees
Definition: A binary tree is a tree such that
every node has at most 2 children
each node is labeled as being either a left chilld or a right child
Recursive definition:
a binary tree is empty;
or it consists of
a node (the root) that stores an element
a binary tree, called the left subtree of T
a binary tree, called the right subtree of T
1 node
2 nodes
4 nodes
d=0
d=1
2^i nodes
d=2
d=3
remove(v):
remove node v, replace it with its child, if any, and return the element stored at v
an error occurs if v has 2 children
addRoot(e):
create and return a new node r storing element e and make r the root of the tree;
an error occurs if the tree is not empty
attach(v,T1, T2):
attach T1 and T2 respectively as the left and right subtrees of the external node v
an error occurs if v is not external
Performance
all
O(1)
left(v)
right(v)
hasLeft(v)
hasRight(v)
isInternal(v)
is External(v)
isRoot(v)
size()
isEmpty()
addRoot(e)
insertLeft(v,e)
insertRight(v,e)
remove(e)
0
1
2
3
4