Trees &amp; BST by University of Toronto

# Trees &amp;amp; BST by University of Toronto - Trees • A...

This preview shows pages 1–6. Sign up to view the full content.

1 Trees • A tree is a data structure used to represent different kinds of data and help solve a number of algorithmic problems • Game trees (i.e., chess ), UNIX directory trees, sorting trees etc • We will study extensively two useful kind of trees: Binary Search Trees and Heaps 2 Trees: Definitions • Trees have nodes . They also have edges that connect the nodes. Between two nodes there is always only one path. Tree nodes Tree edges

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
3 Trees: More Definitions • Trees are rooted. Once the root is defined (by the user) all nodes have a specific level . • Trees have internal nodes and leaves . Every node (except the root) has a parent and it also has zero or more children . level 0 level 1 level 2 level 3 root internal nodes leaves parent and child 4 Binary Trees • A binary tree is one that each node has at most 2 children
5 Binary Trees: Definitions • Nodes in trees can contain keys (letters, numbers, etc) Complete binary tree : the one where leaves are only in last two bottom levels with bottom one placed as far left as possible 14 10 15 12 8 16 7 9 11 13 18 6 Binary Trees: Array Representation • Complete Binary Trees can be represented in memory with the use of an array A so that all nodes can be accessed in O(1) time: – Label nodes sequentially top-to-bottom and left-to-right – Left child of A[i] is at position A[2i] – Right child of A[i] is at position A[2i + 1] – Parent of A[i] is at A[i/2]

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
7 Binary Trees: Array Representation 14 10 15 12 8 16 7 9 11 13 18 1 2 3 4 5 6 7 8 9 10 11 1 2 3 4 5 6 7 8 9 10 11 14 10 16 8 12 15 18 7 9 11 13 Array A: 8 Binary Trees: Pointer Representation • To freely move up and down the tree we need pointers to parent ( NIL for root) and pointers to children ( NIL for leaves) typedef tree_node { int key; struct tree_node *parent; struct tree_node *left, *right; }
9 Tree Traversal: InOrder InOrder is easily described recursively: •Visit left subtree (if there is one) In Order

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
This is the end of the preview. Sign up to access the rest of the document.

## Trees &amp;amp; BST by University of Toronto - Trees • A...

This preview shows document pages 1 - 6. Sign up to view the full document.

View Full Document
Ask a homework question - tutors are online