Trees & BST by University of Toronto

Trees & BST by University of Toronto - Trees • A...

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

View Full Document Right Arrow Icon
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
Background image of page 1

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

View Full DocumentRight Arrow Icon
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
Background image of page 2
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]
Background image of page 3

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

View Full DocumentRight Arrow Icon
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; }
Background image of page 4
9 Tree Traversal: InOrder InOrder is easily described recursively: •Visit left subtree (if there is one) In Order
Background image of page 5

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

View Full DocumentRight Arrow Icon
Image of page 6
This is the end of the preview. Sign up to access the rest of the document.

Page1 / 19

Trees & BST by University of Toronto - Trees • A...

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

View Full Document Right Arrow Icon
Ask a homework question - tutors are online