cs 241 data organization more list and tree fun
play

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


  1. CS 241 Data Organization More List and Tree Fun April 3, 2018

  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 );

  3. Ordered Binary Tree root 4 2 5 1 3

  4. Circular Doubly Linked List 1 2 3 4 5 head First and last nodes wrap around to each other. Null pointer represents an empty list. 1 Length 1 list looks a bit silly. . .

  5. Common Node “Shape” struct Node • In tree, right and { left are greater int data; struct Node* left; and lesser struct Node* right; subtrees. }; • In list, right and left are next and previous nodes.

  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.

  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?

  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; }

  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; }

  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; }

Download Presentation
Download Policy: The content available on the website is offered to you 'AS IS' for your personal information and use only. It cannot be commercialized, licensed, or distributed on other websites without prior consent from the author. To download a presentation, simply click this link. If you encounter any difficulties during the download process, it's possible that the publisher has removed the file from their server.

Recommend


More recommend