10b - TreesSlides

# 10b TreesSlides

This preview shows page 1. Sign up to view the full content.

This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: for 2n-1 nodes. Or log2(n+1) levels for n nodes. So it takes O(log n) checks to find a value. Here's the function to initiate the iteration. void SetIterator(NodePtr root) { curr = root; if (curr != 0) while (curr->left != 0) hil 0) curr = curr->left; curr} void* Next(nodePtr root) { void* rvalue = curr->data; currif (curr->right != 0) // into right subtree (curr{ curr = curr->right; currwhile (curr->left != 0) (currcurr = curr->left; curr} else if (curr->parent == 0) // no parent (currcurr = 0; // we are finished 0; // we are finished else // find ancestor { while (curr->parent != 0 (curr&& (curr->parent)->left != curr) (curr->parent)curr = curr->parent; currcurr = curr->parent; curr} return rvalue; } This assumes every node at each level is filled – a balanced tree. And we can make a tree balanced. As each inserted node takes O(log n) comparisons to find where it goes, the complete fi it th insertion of n values is O(nlog n). Thus, a binary search tree is an O(nlog n) sorting technique with an O(log n) s...
View Full Document

## This document was uploaded on 04/07/2014.

Ask a homework question - tutors are online