Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save SohanChy/88a0251eee4bd375b2a122b878b9d609 to your computer and use it in GitHub Desktop.

Select an option

Save SohanChy/88a0251eee4bd375b2a122b878b9d609 to your computer and use it in GitHub Desktop.
A WIP attempt to implement a max/min heap tree using a binary tree structure (without array).
#include <iostream>
#include <vector>
using namespace std;
struct treeNode {
int data;
treeNode *left, *right;
};
treeNode* getNewTreeNode(int value = 0, treeNode* left = NULL, treeNode* right = NULL)
{
treeNode* Node = new treeNode;
Node->data = value;
Node->left = left;
Node->right = right;
return Node;
}
treeNode* insertNode(treeNode* Node, int value, int *currSize)
{
*currSize = *currSize + 1;
if(Node == NULL)
{
Node = getNewTreeNode(value);
return Node;
}
vector<int> go;
int x = *currSize;
while(x != 0)
{
go.push_back(x%2);
x = x/2;
}
go.pop_back();
treeNode* traverse = Node;
for(int i = go.size() - 1; i > 0; i--)
{
if(go.back() == 0)
{
traverse = traverse->left;
}
else if(go.back() == 1)
{
traverse = traverse->right;
}
go.pop_back();
}
if(go.back() == 0)
{
traverse->left = getNewTreeNode(value);
}
else if(go.back() == 1)
{
traverse->right = getNewTreeNode(value);
}
go.pop_back();
return Node;
}
void BST_preorder(treeNode* Node, vector<int> *vec = NULL)
{
if(Node->left != NULL)
{
BST_preorder(Node->left,vec);
}
if(vec == NULL)
{
cout<<Node->data<<" ";
}
else
{
vec->push_back(Node->data);
}
if(Node->right != NULL)
{
BST_preorder(Node->right,vec);
}
return;
}
int main()
{
treeNode* root = NULL;
int treeData[] = {7,12,13,20,5,6,11,2,1,3,6,19,25,21,22};
int tDsize = sizeof(treeData)/sizeof(int);
int countSize = 0;
for(int i = 0; i<tDsize; i++)
{
root = insertNode(root,treeData[i],&countSize);
}
BST_preorder(root);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment