Docsity

Data Structures: Binary Trees and Binary Search Trees in C, Slides of Computer Engineering and Programming

Partial preview of the text

Download Data Structures: Binary Trees and Binary Search Trees in C and more Slides Computer Engineering and Programming in PDF only on Docsity!

Computer Programming Techniques

Overview

1. Tree Example

2. Binary Trees

3. Binary Trees in C

4. Tree Traversal

5. Binary Search Trees

6. Searching a BST

7. Insertion into a BST

8. Deletion from a BST

2. Binary Trees

 Each element (node) of the tree may have

0 ,1 or 2 successors.

a

c

d e f g

b

i j k

h

Binary Tree Jargon

 a is the root of the tree

 b, c are the children of a

 left subtree of a: the tree whose root is b

 right subtree of a: the tree whose root is c

 d, e, h, i, j are descendents of b

 every node is a descendent of a (the root)

 h, i, j, k, g are the leaves of the tree

Some Binary Tree ADT Operations

 create an empty tree

 build a new tree from a data value and two subtrees

 deletion

 insertion

 check to see if a tree is empty

 print out all the elements in a tree

3. Binary Trees in C

3 .1. Binary Tree Type

3 .2. Examples

3 .3. Some Functions

3 .4. Size of a Binary Tree

3 .5. Height of a Binary Tree

3 .2. Examples

TREE t;

The empty tree:

t = NULL;

A tree with a single element 2:

t t^ NULL t 2 N N

A more complicated tree:

t 2 4 7

N N N

N N

int value(TREE t) { if (isEmptyTree(t)) { printf(“Tree is empty\n”); return -1; } else return t->data; } TREE mkEmpty(void) /* return an empty tree */ { return NULL; }

TREE mkTree(int x, TREE leftT, TREE rightT) /* make a new tree from a data value x and two existing trees */ { TREE temp; temp = malloc(sizeof(TREENODE)); temp->data = x; temp->leftptr = leftT; temp->rightptr = rightT; return temp; }

3 .4. Size of a Binary Tree

 an empty tree has 0 size

 a non-empty tree has one node plus the number of

elements in the subtrees

n

tree

tree

size(tree) =

1 + size(tree1) + size(tree2)

C Version

int size(TREE t) { if (isEmptyTree(t)) return 0; else return (1 + size(lsTree(t))

  • size(rsTree(t)) ); }

3 .5. Height of a Binary Tree

 the height of an empty tree is 0

 the height of a non-empty tree is 1 plus the height

of the highest subtree

n

tree

tree

height of tree height of tree

height(tree) = 1 +

max(height(tree1),

height(tree2))

C Version

int height(TREE t) { if(isEmptyTree(t)) return 0; else return (1 + max(height(lsTree(t)), height(rsTree(t)))); }