Skip to content

Instantly share code, notes, and snippets.

@amankharwal
Created March 20, 2021 08:37
Show Gist options
  • Save amankharwal/a624fe31ac669a1aa9d2ab4604063bf7 to your computer and use it in GitHub Desktop.
Save amankharwal/a624fe31ac669a1aa9d2ab4604063bf7 to your computer and use it in GitHub Desktop.
#include <iostream>
using namespace std;
typedef struct binary_tree_node{
int v;
struct binary_tree_node *left;
struct binary_tree_node *right;
}
BTNode;
BTNode *create_binary_tree_node(int v){
BTNode *p = new BTNode;
if(p != NULL){
p->v = v;
p->left = NULL;
p->right = NULL;
}
return p;
}
void create_balanced_bin_tree(BTNode **root, int arr[], int start, int end){
if(start <= end){
int mid = (start + end + 1) / 2;
*root = create_binary_tree_node(arr[mid]);
create_balanced_bin_tree(&((*root)->left), arr, start, mid - 1);
create_balanced_bin_tree(&((*root)->right), arr, mid + 1, end);
}
}
void print_binary_tree(BTNode *root){
if(root != NULL){
cout << root->v;
print_binary_tree(root->left);
cout << endl;
print_binary_tree(root->right);
cout << endl;
}
}
int main(int argc, char* argv[])
{
int arr[30];
for(int i = 0; i < 30; i ++){
arr[i] = i;
}
BTNode *root = NULL;
create_balanced_bin_tree(&root, arr, 0, 29);
print_binary_tree(root);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment