Tree Inserting & Erasing

Tree Inserting & Erasing - Lecture 17 Tree...

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

View Full Document Right Arrow Icon
1 Lecture 17: Tree Inserting / Erasing PIC 10B Todd Wittman Inserting A Node s A new value is always inserted into the tree as a leaf node. s We essentially search the tree for where our new value should go until we hit NULL. s Then we back up one and make it a new parent. s If the tree was initially empty, make this the new root. s Inserting is O(h). 15 5 16 3 12 7 20 18 23 13 10 6
Background image of page 1

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

View Full DocumentRight Arrow Icon
2 template <typename T> void Tree<T> :: insert (T value) { TreeNode<T>* newNode = new TreeNode<T>(value); TreeNode<T>* parentNode = NULL; TreeNode<T>* pos = root; while (pos != NULL) { parentNode = pos; if ( value <= (pos->data) ) pos = pos->left; else pos = pos->right; } if (parentNode == NULL) root = newNode; else if ( value <= (parentNode->data) ) parentNode->left = newNode; else parentNode->right = newNode; return; } parentNode points to the parent of pos pos traces for the new value until we fall off the tree Check if we made a new root. Make newNode the child of parentNode Erasing: 0 or 1 children s There are 3 cases. s Case 1 : The node to erase has no children. Simply make its parent point to NULL. 15 16 15 16 20 We have to check if we change parent's left or right pointer. s Case 2 : The node to erase has 1 child. We can "splice" out the node with its child.
Background image of page 2
Image of page 3
This is the end of the preview. Sign up to access the rest of the document.

Page1 / 7

Tree Inserting &amp; Erasing - Lecture 17 Tree...

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

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