last. Upon termination of the
traversal, this variable contains the deepest element.
The code is given below.
The relevant files are ebinary.*.
template <class T> T BinaryTree<T>::DeepestElement() {// Return the deepest element in the tree. // Throw BadInput exception is the tree is empty. if (!root) // no deepest element throw BadInput(); // do a level-order traversal keeping track of // the most recently seen element LinkedQueue<BinaryTreeNode<T>*> Q; BinaryTreeNode<T> *t = root; T last; // last element encountered while (t) { last = t->data; if (t->LeftChild) Q.Add(t->LeftChild); if (t->RightChild) Q.Add(t->RightChild); try {Q.Delete(t);} catch (OutOfBounds) {return last;} } }
n), where n
is the number of nodes in the binary tree.
ChangeMin is very
similar to that for
DeleteMin.
The code is given below and in
the files minheap4.*.
template<class T> void MinHeap<T>::Initialize(T a[], int size, int ArraySize) {// Initialize min heap to array a. delete [] heap; heap = a; CurrentSize = size; MaxSize = ArraySize; // make into a min heap for (int i = CurrentSize/2; i >= 1; i--) { T y = heap[i]; // root of subtree // find place to put y int c = 2*i; // parent of c is target // location for y while (c <= CurrentSize) { // make c point to smaller sibling if (c < CurrentSize && heap[c] > heap[c+1]) c++; // can we put y in heap[c/2]? if (y <= heap[c]) break; // yes // no heap[c/2] = heap[c]; // move heap[c] up c *= 2; // move c down a level } heap[c/2] = y; } }
CurrentSize =
n elements is
Theta(log n). The change min algorithm spends constant
time at a level and goes through at most as many levels as the
height of the min heap. So the complexity is
O(log n).
A
is the root of the binary tree.
Also A comes between the left and right subtree in
inorder. So the left subtree is empy
and BCDEFGHIJ is the inorder output of the
right subtree.
The next element in preorder
D is the root of the left subtree
unless the left subtree is empty (in which case it is the root
of the right subtree). Using this information
and what we have already learnt from the inorder sequence, we
see that D is the root of the right subtree
and BC are in the left subtree of
D and EFGHIJ are
in its right subtree.
Proceeding in this way we can construct the entire binary tree.
The unique binary tree from which the given inorder and preorder outputs
came is:
A
\
D
/ \
B J
\ /
C G
/ \
F H
/ \
E I
feedback form |
permissions |
international |
locate your campus rep |
request a review copy
Copyright ©2001 The McGraw-Hill Companies.
digital solutions |
publish with us |
customer service |
mhhe home
Any use is subject to the
Terms of Use and Privacy Policy.
McGraw-Hill Higher Education is one of the many fine businesses of the
The McGraw-Hill Companies.