CS 241 Data Organization More List and Tree Fun April 3, 2018 - - PowerPoint PPT Presentation

cs 241 data organization more list and tree fun
SMART_READER_LITE
LIVE PREVIEW

CS 241 Data Organization More List and Tree Fun April 3, 2018 - - PowerPoint PPT Presentation

CS 241 Data Organization More List and Tree Fun April 3, 2018 Pointer Changing Code What do we do if a function needs to change one of the pointer parameters passed to it? Assume we have struct Node* root that points to a tree. We could


slide-1
SLIDE 1

CS 241 Data Organization More List and Tree Fun

April 3, 2018

slide-2
SLIDE 2

Pointer Changing Code

What do we do if a function needs to change one of the pointer parameters passed to it? Assume we have struct Node* root that points to a tree.

  • We could use pointers to pointers.

void changeTree(struct Node ** node ); changeTree (& root );

  • We could have the function return new pointer

value.

struct Node* changeTree(struct Node* node ); root = changeTree(root );

slide-3
SLIDE 3

Ordered Binary Tree

root 4 1 2 3 5

slide-4
SLIDE 4

Circular Doubly Linked List

head 1 2 5 3 4

First and last nodes wrap around to each other. Null pointer represents an empty list. Length 1 list looks a bit silly. . .

1

slide-5
SLIDE 5

Common Node “Shape”

struct Node { int data; struct Node* left; struct Node* right; };

  • In tree, right and

left are greater and lesser subtrees.

  • In list, right and

left are next and previous nodes.

slide-6
SLIDE 6

Tree to List Challenge

Take ordered binary tree and rearrange the pointers to make a circular doubly linked list. This operation can be done in O(n) time.

slide-7
SLIDE 7

Tree to List

/* Given root node of binary tree , * convert to list and return head node. */ struct Node* treeToList(struct Node* node );

  • How will this function work?
  • What helper function(s) will we want?
slide-8
SLIDE 8

List helpers

/* Given two circular doubly linked lists , * append them and return new head node. */ struct Node* joinLists(struct Node* a, struct Node* b); /* Join two nodes so second follows

  • first. */

void joinNodes(struct Node* a, struct Node* b) { a->right = b; b->left = a; }

slide-9
SLIDE 9

joinLists

struct Node* joinLists(struct Node* a, struct Node* b) { struct Node* aLast; struct Node* bLast; if(a == NULL) return b; else if(b == NULL) return a; else { aLast = a->left; bLast = b->left; joinNodes(aLast , b); joinNodes(bLast , a); } return a; }

slide-10
SLIDE 10

treeToList

struct Node* treeToList(struct Node* node) { struct Node* left; struct Node* right; if(node != NULL) { left = treeToList(node ->left ); right = treeToList(node ->right ); node ->left = node; node ->right = node; node = joinLists(left , node ); node = joinLists(node , right ); } return node; }