Post order traversal of min heap

Nov 3, 2019 at 12:49pm
The code is showing the right children for data: 1,2,3,4,5
but shows wrong left and right children for data: 10,8,3,5,12
Kindly help!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#include <iostream>
using namespace std;
using namespace std;
void min_heapify(int *a, int i, int n)
{
	int j, temp;
	temp = a[i];
	j = 2 * i;
	while (j <= n)
	{
		if (j < n && a[j + 1] < a[j])
			j = j + 1;
		if (temp < a[j])
			break;
		else if (temp >= a[j])
		{
			a[j / 2] = a[j];
			j = 2 * j;
		}
	}
	a[j / 2] = temp;
	return;
}
void build_minheap(int *a, int n)
{
	int i;
	for (i = n / 2; i >= 1; i--)
	{
		min_heapify(a, i, n);
	}
}
void postorder(int arr[], int size, int i) {
	if (i > size)
		return;
	if (i <= size) {
			cout << "parrent: " << arr[i];
			if (2 * i  <= size)
				cout << "\tleft: " << arr[2 * i];
			if (2 * i + 1 <= size)
				cout << "\tright: " << arr[2 * i + 1];

		}
	cout << endl;
	postorder(arr, size, i + 1);
}
int main()
{
	int n, i, x;
	cout << "enter no of elements of array\n";
	cin >> n;
	int a[20];
	for (i = 1; i <= n; i++)
	{
		cout << "enter element" << (i) << endl;
		cin >> a[i];
	}
	build_minheap(a, n);
	cout << "Min Heap\n";
	postorder(a, n, 1);
	/*for (i = 1; i <= n; i++)
	{
		cout << a[i] << endl;
	}*/
	system("pause");
}
Nov 3, 2019 at 2:02pm
In C++, arrays are indexed from 0 to size-1. Your code uses indexes 1 to size. You should get in the habit of using the standard index values.

That said, your code works fine for me.
$ ./foo
enter no of elements of array
5
enter element1
10
enter element2
8
enter element3
3
enter element4
5
enter element5
12
Min Heap
parrent: 3      left: 5 right: 10
parrent: 5      left: 8 right: 12
parrent: 10
parrent: 8
parrent: 12
sh: pause: command not found

Topic archived. No new replies allowed.