{[ promptMessage ]}

Bookmark it

{[ promptMessage ]}

Tree Inserting &amp; Erasing

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

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

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

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

View Full Document
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 square6 There are 3 cases. square6 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. square6 Case 2 : The node to erase has 1 child. We can "splice" out the node with its child.
This is the end of the preview. Sign up to access the rest of the document.

{[ snackBarMessage ]}