-
Notifications
You must be signed in to change notification settings - Fork 160
/
Copy pathHeapify a binary tree.cpp
85 lines (55 loc) · 1.39 KB
/
Heapify a binary tree.cpp
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
/*
Given a binary tree with integers, heapify the binary tree.
*/
/*
solution: recursive call to the leaf, and shiftup.
O(n) time
*/
#include<iostream>
using namespace std;
struct NODE {
int val;
NODE* plft;
NODE* prgt;
NODE(int n) : val(n), plft(NULL), prgt(NULL) {}
};
void ShiftUp(NODE *node) {
if(!node) return;
NODE *largest = node;
//find the largest node
if (node->plft != NULL && largest->val < node->plft->val) {
largest = node->plft;
}
if (node->prgt != NULL && largest->val < node->prgt->val) {
largest = node->prgt;
}
// if root has the largest value, return
if (largest == node) return;
//if not, swap the node's value with largest value
int tmp = node->val;
node->val = largest->val;
largest->val = tmp;
ShiftUp(largest);
}
void HeapifyBinaryTree(NODE *root) {
if (!root) return;
if (root->plft) {
HeapifyBinaryTree(root->plft);
}
if (root->prgt) {
HeapifyBinaryTree(root->prgt);
}
ShiftUp(root);
}
int main() {
NODE *root = new NODE(1);
root->plft = new NODE(2);
root->prgt = new NODE(3);
root->prgt->plft = new NODE(5);
HeapifyBinaryTree(root);
cout<<root->val<<endl;
cout<<root->plft->val<<endl;
cout<<root->prgt->val<<endl;
cout<<root->prgt->plft->val<<endl;
return 0;
}