C++, How to create and draw a Binary Tree then traverse it in Pre-Order - c++

How do I create a Binary Tree and draw it using a Pre-Order Traversal strategy? The root would be the first number going in.
I have a set of numbers: 48 32 51 54 31 24 39. 48 would be the root. How are the child nodes pushed onto the Binary Tree in a Pre-Order traversal?

Imagine the following sub-problem. You have a set of numbers:
N A1...AX B1...BY
You know that N is the root of the corresponding tree. All you need to know is what numbers form the left sub-tree. Obviously the rest of the numbers form the right sub-tree.
If you remember the properties of a binary-search trees, you would know that elements of the left sub-tree have values smaller than the root (while the ones on the right have values bigger).
Therefore, the left sub-tree is the sequence of numbers that are smaller than (or possibly equal to) N. The rest of the numbers are in the right sub-tree.
Recursively solve for
A1...AX
and
B1...BY
For example given:
10 1 5 2 9 3 1 6 4 11 15 12 19 20
You get:
root: 10
left sub-tree: 1 5 2 9 3 1 6 4
right sub-tree: 11 15 12 19 20

Say you have the following binary tree:
A
/ \
B C
/ \ / \
D E F G
/ \
H I
A Pre-Order Traversal goes NODE, LEFT, RIGHT.
So Pre-Order of this binary tree would be: A B D E H I C F G
For more details on how to implement this in C++: https://stackoverflow.com/a/17658699/445131

Related

What is the tree-structure of a heap?

I'm reading Nicolai M. Josuttis's "The C++ standard library, a tutorial and reference", ed2.
He explains the heap data structure and related STL functions in page 607:
The program has the following output:
on entry: 3 4 5 6 7 5 6 7 8 9 1 2 3 4
after make_heap(): 9 8 6 7 7 5 5 3 6 4 1 2 3 4
after pop_heap(): 8 7 6 7 4 5 5 3 6 4 1 2 3
after push_heap(): 17 7 8 7 4 5 6 3 6 4 1 2 3 5
after sort_heap(): 1 2 3 3 4 4 5 5 6 6 7 7 8 17
I'm wondering how could this be figured out? for example, why the leaf "4" under path 9-6-5-4 is the left side child of node "5", not the right side one? And after pop_heap what's the tree structure then? In IDE debugging mode I could only see see the content of the vector, is there a way to figure out the tree structure?
why the leaf "4" under path 9-6-5-4 is the left side child of node "5", not the right side one?
Because if it was on the right side, that would mean there is a gap in the underlying vector. The tree structure is for illustrative purposes only. It is not a representation of how the heap is actually stored. The tree structure is mapped onto the underlying vector via a simple mathematical formula.
The root node of the tree is the first element of the vector (index 0). The index of the left child of a node is obtained from its parent's index by the simple formula: i * 2 + 1. And the index of the right child is obtained by i * 2 + 2.
And after pop_heap what's the tree structure then?
The root node is swapped with the greater of its two children1, and this is repeated until it is at the bottom of the tree. Then it is swapped with the last element. This element is then pushed up the tree, if necessary, by swapping with its parent if it is greater.
The root node is swapped with the last element of the heap. Then, this element is pushed down the heap by swapping with the greater of its two children1. This is repeated until it is in the correct position (i.e. it is not less than either of its children).
So after pop_heap, your tree looks like this:
----- 8 -----
| |
---7--- ---6---
| | | |
-7- -4- -5- x5
| | | | | | x
3 6 4 1 2 3 9
The 9 is not actually part of the heap anymore, but it is still part of the vector until you erase it, via a call pop_back or similar.
1. if the children are equal, as in the case of the adjacent 7's in the tree in your example, it could go either way. I believe that std::pop_heap sends it to the right, though I'm not sure if this is implementation defined
The first element in the vector is the root at index 0. Its left child is at index 1 and its right child at index 2. In general: left_child(i) = 2 * i + 1 and right_child(i) = 2 * i + 2 and parent(i) = floor((i - 1) / 2)
Another way to think about it is the heap fills each level from left to right in the tree. Following the elements in the vector the first level is 9 (1 value), second level 8 6 (2 values) and third level 7 7 5 5 (4 values), and so on. Both these ways will help you draw the heap in a tree structure when given a vector.

How to know if an index in a binary heap is on an odd level?

If I have a binary heap , with the typical properties of left neighbor of position "pos" being (2*pos)+1 while right neighbor is (2*pos)+2 and parent node in (pos-1) )/ 2, how can I efficiently determine if a given index represents a node on an odd level (with the level of the root being level 0) ?
(Disclaimer: This is a more complete answer based on Jarod42's comment.)
The formula you want is:
floor(log2(pos+1)) mod 2
To understand why, look at the levels of the first few nodes:
0 Level: 0
1 2 1
3 4 5 6 2
7 8 9 10 11 12 13 14 3
0 -> 0
1 -> 1
2 -> 1
3 -> 2
...
6 -> 2
7 -> 3
...
The first step is to find a function that will map node numbers to level numbers in this way. Adding one to the number and taking a base 2 logarithm will give you almost (but not quite) what you want:
log2 (0+1) = log2 1 = 0
log2 (1+1) = log2 2 = 1
log2 (2+1) = log2 3 = 1.6 (roughly)
log2 (3+1) = log2 4 = 2
....
log2 (6+1) = log2 7 = 2.8 (roughly)
log2 (7+1) = log2 8 = 3
You can see from this that rounding down to the nearest integer in each case will give you the level of each node, hence giving us floor(log2(pos+1)).
As Jarod42 said, it's then a case of looking at the parity of the level number, which just involves taking the number mod 2. This will give either 0 (the level is even) or 1 (the level is odd).

How to balance between two arrays such as the difference is minimized?

I have an array A[]={3,2,5,11,17} and B[]={2,3,6}, size of B is always less than A. Now I have to map from every element B to distinct elements of A such that the total difference sum( abs(Bi-Aj) ) becomes minimum (Where Bi has been mapped to Aj). What is the type of algorithm?
For the example input, I could select, 2->2=0 , 3->3=0 and then 6->5=1. So the total cost is 0+0+1 = 1. I have been thinking sorting both the arrays and then take the first sizeof B elements from the A. Will this work?
It can be thought of as an unbalanced Assignment Problem.
The cost matrix shall be the difference in values of B[i] and A[j]. You can add dummy elements to B so that the problem becomes balanced and put the costs associated very high.
Then Hungarian Algorithm can be applied to solve it.
For the example case A[]={3,2,5,11,17} and B[]={2,3,6} the cost matrix shall be:
. 3 2 5 11 17
2 1 0 3 9 15
3 0 1 2 8 14
6 3 4 1 5 11
d1 16 16 16 16 16
d2 16 16 16 16 16

Convert to a complete BST function

I need to save data in the bst to a sorted array, then, the ConvertToCompleteBST function clears current tree and uses the array to re-insert the values recursively by inserting the middle value in each call.
InsertRecursively(data_array,size);
For example, if the array was
[5 7 10 12 16 18 30]
then InsertRecursively([5 7 10 12 16 18 30],7) is called first,
the middle is 12 so 12 is the first one is inserted into the tree. Then in the recursive call , it will do the same but for
InsertRecursively([5 7 10],3)
InsertRecursively([16 18 30],3)
Then, InsertRecursively([5 7 10],3) will lead to inserting the node 7 and two other recursive calls
InsertRecursively([5],1) >> lead to inserting node 5
InsertRecursively([10],1) >> lead to inserting node 10
When size is 1, it will stop the recursive call.
I have no idea how to implement the insertRecursively function

ant colony optimisation for 01 MKP

I'm trying to implement an ACO for 01MKP. My input values are from the OR-Library mknap1.txt. According to my algorithm, first I choose an item randomly. then i calculate the probabilities for all other items on the construction graph. the probability equation depends on pheremon level and the heuristic information.
p[i]=(tau[i]*n[i]/Σ(tau[i]*n[i]).
my pheremon matrix's cells have a constant value at initial (0.2). for this reason when i try to find the next item to go, pheremon matrix is becomes ineffective because of 0.2. so, my probability function determines the next item to go, checking the heuristic information. As you know, the heuristic information equation is
n[i]=profit[i]/Ravg.
(Ravg is the average of the resource constraints). for this reason my prob. functions chooses the item which has biggest profit value. (Lets say at first iteration my algorithm selected an item randomly which has 600 profit. then at the second iteration, chooses the 2400 profit value. But, in OR-Library, the item which has 2400 profit value causes the resource violation. Whatever I do, the second chosen is being the item which has 2400 profit.
is there anything wrong my algorithm? I hope ppl who know somethings about ACO, should help me. Thanks in advance.
Input values:
6 10 3800//no of items (n) / no of resources (m) // the optimal value
100 600 1200 2400 500 2000//profits of items (6)
8 12 13 64 22 41//resource constraints matrix (m*n)
8 12 13 75 22 41
3 6 4 18 6 4
5 10 8 32 6 12
5 13 8 42 6 20
5 13 8 48 6 20
0 0 0 0 8 0
3 0 4 0 8 0
3 2 4 0 8 4
3 2 4 8 8 4
80 96 20 36 44 48 10 18 22 24//resource capacities.
My algorithm:
for i=0 to max_ant
for j=0; to item_number
if j==0
{
item=rand()%n
ant[i].value+=profit[item]
ant[i].visited[j]=item
}
else
{
calculate probabilities for all the other items in P[0..n]
find the biggest P value.
item=biggest P's item.
check if it is in visited list
check if it causes resource constraint.
if everthing is ok:
ant[i].value+=profit[item]
ant[i].visited[j]=item
}//end of else
}//next j
update pheremon matrix => tau[a][b]=rou*tau[a][b]+deltaTou
}//next i