Skip to content

Instantly share code, notes, and snippets.

@amankharwal
Last active Feb 11, 2021
Embed
What would you like to do?
#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