swapTree method.
The public method can be defined as below:
public void swapChildren()
{swapChildren(root);}
The private method is a class (i.e., static) method
that does the actual swapping of children
by performing a postorder traversal. The code is given below.
private static void swapChildren(BinaryTreeNode 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 != null) { // swap in the left subtree swapChildren(t.leftChild); // swap in the right subtree swapChildren(t.rightChild); // swap children of t BinaryTreeNode temp = t.rightChild; t.rightChild = t.leftChild; t.leftChild = temp; } }
O(n), where n
is the number of nodes in the binary tree.
/** put theElement into the heap */ public void put(Comparable theElement) { // increase array size if necessary if (size == heap.length - 1) heap = (Comparable []) ChangeArraySize.changeSize1D (heap, 2 * heap.length); // find place for theElement // i starts at new leaf and moves up tree int i = ++size; while (i != 1 && heap[i / 2].greaterThan(theElement)) { // cannot put theElement in heap[i] heap[i] = heap[i / 2]; // move element down i /= 2; // move to parent } heap[i] = theElement; }
size =
n elements is
O(log n). The put method 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