trees n.
Download
Skip this Video
Loading SlideShow in 5 Seconds..
Trees PowerPoint Presentation
Download Presentation
Trees

Loading in 2 Seconds...

play fullscreen
1 / 36

Trees - PowerPoint PPT Presentation


  • 89 Views
  • Uploaded on

Trees. CS-212 Dick Steflik. What is a Tree. A tree is a finite set of one or more nodes such that: There is a specially designated node called the root

loader
I am the owner, or an agent authorized to act on behalf of the owner, of the copyrighted work described.
capcha
Download Presentation

PowerPoint Slideshow about 'Trees' - matty


An Image/Link below is provided (as is) to download presentation

Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.


- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript
trees

Trees

CS-212

Dick Steflik

what is a tree
What is a Tree
  • A tree is a finite set of one or more nodes such that:
    • There is a specially designated node called the root
    • The remaining nodes are partitioned into n>0 disjoint sets T1,..,Tn, where each of these sets is a tree. T1,..,Tn are the subtrees of the root.
tree terms
Tree Terms

Root

A

A is the parent of B and C

B and C are children of A

B

C

B and C are siblings

height (h)

interior nodes

F

E

D

G

H

leaf nodes

(exterior nodes)

slide5

height - the number of nodes in the longest path going from the root to the furthest leaf

parent - any node in the tree at the next higher level in the tree

child - any node in the tree at the next lower level in the tree

siblings - any nodes in the tree having a common parent

order - the number of children in the node having the largest number of children

binary tree - any order 2 tree

binary search tree - any binary tree having the search tree property

things represented as trees
Things represented as trees
  • Table of Contents
  • Subassembly diagrams
  • Genealogy diagrams
  • Pedigree diagrams
  • Tournament playoffs
  • Graphics representation
  • Organizational charts
nodal structure options
Nodal Structure Options

If we know the maximum order that an arbitrary tree is supposed to be we could allocate our data content and a child pointer for each possible child

Ex suppose max. order = 5

each node would look like:

child

1

child

4

child

5

child

3

child

2

Data

If our tree has many nodes that have less than 5 children this

representation could be very wasteful considering that each child

pointer requires 4 bytes of storage.

Is there a better, less wasteful representation?

as it turns out yes there is
As it turns out, YES there is

The lowly order 2 (binary) tree can be used to represent any order n tree. and we can make the statement that:

For any general tree, there is an equivalent binary tree

To do this we must visualize an order 2 tree differently; instead of as a collection of parents and children we view it as parent, leftmost

child and that child’s siblings

This:

Instead of this :

A

A

B

C

B

C

D

D

why do we want to do this
Why do we want to do this?

It turns out that order 2 tree have a very nice structure in that there are only two choices to

make; Right or Left. This makes it easier to design algorithms for them.

To explore this let us look at the problem of creating an algorithm for visiting every node in a tree in some predictable order. This problem is called Traversal and can be accomplished with the following the following algorithm.

1. start at the root and

2. follow all of the left links until you can’t go any farther

3. back-up one node and try going right, if you can repeat steps 2 and 3, if you can’t repeat step 3

node structure static
Node Structure (Static)

typedef struct {

Element data;

Link left

Link right;

} Node;

typedef struct {

int numFree;

int numInTree;

Link free;

Link root;

Node Nodes[NUMNODES];

} tree;

node structure dynamic
Node Structure (Dynamic)

typedef node * Tree;

struct Node{

element e;

Tree left;

Tree right;

};

static or dynamic
Static or Dynamic ?
  • Static
    • you know the maximum number of nodes
      • not likely to change
  • Dynamic
    • size of the tree will change frequently
    • slightly faster than static
      • traversing pointers is faster than calculating addresses for array indexing
traversal
Traversal

Notice that each node is visited 3 times

A

3

1

Were we to print out the node data in the first visit to each node the printout would be : ABC

2

Were we to printout the node data on the second visit to each node the printout would be: BAC

1

3

3

C

B

1

Were we to printout the node data on the third visit to each node the printout would be: BCA

2

2

These are called the: preorder, inorder and postorder traversals respevtively

pre order traversal
Pre-order Traversal

void preorder( tnode * t)

{

if (t != NULL)

{

printf (“ %d “, t -> data );

preorder(t -> left);

preorder(t -> right);

}

}

in order traversal
In-order Traversal

void inorder( tnode * t)

{

if (t != NULL)

{

inorder(t -> left);

printf(“ %d “, t -> data );

inorder(t -> right;

}

}

post order traversal
Post-order Traversal

void postorder( tnode * t)

{

if (t != NULL)

{

postorder(t -> left);

postorder(t -> right);

printf(“ %d “, t -> data );

}

}

notice that
Notice that...

the first node visited on the pre-order traversal ia always the root

the left-most node in the tree is the first node on the inorder traversal

the last node visited on the inorder traversal is the rightmost node in the tree

the last node visited on the postorder traversal is the root

Knowing this and given any two traversal paths the tree can be constructed…….

armed with this information
Armed with this information…
  • We should be able to construct the tree that produced any pair of traversal paths
insertion
Insertion

Tree insert(Tree p , int v)

{

if (p == NULL)

{

p = (Tree) malloc(sizeof(struct Node));

p->data = v;

p->right = NULL;

p->left = NULL;

}

else if (v < p->data)

p->left = insert(p->left,v);

else if (v > p->data)

p->right = insert(p->right,v);

return p;

};

search
search

Tree search(Tree p , int v)

{

if ((p == NULL) || (v == p->data))

{

printf("Found\n");

return p;

}

if (v < p->data)

return search(p->left,v);

else

return search(p->right,v);

};

slide21
Note:
    • If the tree is being used to represent a set the search function would be better named isMember( )
priority queue
Priority Queue
  • BST could be used as a Priority Queue
    • Needs functions: insert( ) findMin( ) removeMin( ) or findMax( ) removeMax( )
  • Node with minimum priority is leftmost node
  • Node with maximum priority is rightmost node
deletion
Three cases we need to consider:

V has no children

Remove v

V has one child

Swap v with child and do 1

V has 2 children

Swap v with successor

leftmost node in right subtree

Do case 1 or case 2 to delete

Deletion
deletion1
Deletion

20

10

25

30

15

5

12

heaps
Heaps
  • The heap property:
    • max heap: the largest key is at the root; at each node the keys of the children must be less than the key of the parent
    • min heap: the smallest key is at the root; the keys of the children must be greater than the key of the parent
    • used as a priority queue; and the basis for heap sort
visualize
Visualize

a one dimensional array as a tree as follows (the array contains the keys)

0

0

1

2

3

4

5

6

1

2

3

4

5

6

to find the child or parent
To Find the child or parent
  • iL = (2*iP)+1
  • iR = (2*iP)+2
  • iP = (iC-1)/2
adding a key
Adding a Key
  • Tree is complete (i.e. it fills up in ascending index positions)
  • Must keep track of where end of tree currently is
  • Insert new key at end of tree, then bubble it up to it proper location by comparing to the parent’s key and swapping if necessary
  • This gives O(log2n) for each add.
deleting a key
Deleting a key
  • Swap the last key with the root and remove the last key
  • Recursivly push the root down to its proper level by comparing it to its children and swapping with smallest child
  • This gives O(log2n) for each deletion
insuring o log 2 n performance
Insuring O(log2n) performance
  • The main problem with BST is that its hard to insure optimum performance.
    • shape of the tree is very dependent on the order the keys were inserted in
      • trees tend to degenerate to varying degrees
the solution self balancing trees
The solution - Self-balancing trees
  • AVL Trees
  • Red/Black Trees
  • 2-3 trees
  • 2-3-4 trees
  • B-Trees
avl trees
AVL Trees
  • Height balanced
    • at every node the allowable difference in height between the right and left subtree is one
    • an additional piece of data is required
      • balance factor
        • value = 0 : right and left subtrees are same height
        • value = 1 : right subtree is one higher
        • value = -1 : left subtree is one higher
        • value = 2 or -2 : tree need to be rebalanced
avl method
AVL Method
  • Insertion is pretty much like a BST recursive insertion but on the way out (unwinding the recursion) check and adjust the balance factors, if a difference of 2 or -2 is found rebalance the tree by doing an RR, LL, RL or LR rotation
out of balance conditions
Out of Balance Conditions
  • insertion into left subtree of left child of x called LL (mirror image of RR) fix with a rotateRight
  • insertion into right subtree of right child of x called RR (mirror image of LL) fix with a rotateLeft
  • insertion into left subtree of right child of x called LR (mirror image of RL) fix with a rotateLeft , rotateRight
  • insertion into right subtree of left child of x called RL (mirror image of LR) fix with a rotateRight , rotateLeft
slide35
LL

k2

k1

k2

k1

C

C

A

B

B

B

A

C

A

Node * rotateLeft(Node * k2)

{ Node * k1 = k2->left;

k2 ->left = k1->right;

k1->right = k2;

return k1 }

slide36
LR

k2

k3

k3

k2

k1

k3

k1

k2

k1

D

D

B

C

C

A

A

D

B

C

B

A

Node * DoubleRotateLeft( Node * k3)

{ k3->left = RotateLeft(k3->left);

return RotateRight(k3); }