Skip to content

Instantly share code, notes, and snippets.

@amankharwal
Last active February 11, 2021 14:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save amankharwal/c46312b9201bb59414bfdb0484371e91 to your computer and use it in GitHub Desktop.
Save amankharwal/c46312b9201bb59414bfdb0484371e91 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