SwapTree function.
The public function can be defined inline as below:
BinaryTree<T>& SwapChildren()
{SwapChildren(root); return *this;}
The private function that does the actual swapping of children
by performing a postorder traversal is given below.
The relevant files are bbinary.*.
template<class T> void BinaryTree<T>::SwapChildren(BinaryTreeNode<T> * &t) {// Swap the children of every node in the subtree t. // Do a postorder traversal; swap left and right child // pointers in the visit step. if (t) {// t is not null SwapChildren(t->LeftChild); SwapChildren(t->RightChild); Swap(t->LeftChild, t->RightChild); } }
n), where n
is the number of nodes in the binary tree.
minheap.*.
template<class T> MinHeap<T>& MinHeap<T>::Insert(const T& x) {// Insert x into the min heap. if (CurrentSize == MaxSize) throw NoMem(); // no space // find place for x // i starts at new leaf and moves up tree int i = ++CurrentSize; while (i != 1 && x < heap[i/2]) { // cannot put x in heap[i] heap[i] = heap[i/2]; // move element down i /= 2; // move to parent } heap[i] = x; return *this; }
CurrentSize =
n elements is
Theta(log n). The insert 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).
e to the root are children of the original root.
F
is the root of the binary tree.
Also F comes between the left and right subtree in
inorder. So ABCDE is the inorder output of the
left subtree and GHIJ is the inorder output of the
right subtree. The next element in postorder
I is the root of the right subtree
unless the right subtree is empty (in which case it is the root
of the left subtree). Using this information
and what we have already learnt from the inorder sequence, we
see that I is the root of the right subtree
and GH are in the left subtree of
I and J 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 postorder outputs
came is:
F
/ \
E I
/ / \
A G J
\ \
C H
/ \
B D
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.