-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconvertToBinaryTree.cpp
More file actions
56 lines (39 loc) · 1.02 KB
/
convertToBinaryTree.cpp
File metadata and controls
56 lines (39 loc) · 1.02 KB
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
#include <iostream>
#include <vector>
#include <stdlib.h>
using namespace std;
struct node {
struct node* left;
struct node* right;
int data;
};
struct node* insert(int data){
struct node* root = (struct node*) malloc(sizeof(struct node));
root->data = data;
root->left = NULL;
root->right = NULL;
return root;
}
void inOrder(struct node* root) {
if (root == NULL) return;
inOrder(root->left);
cout<<root->data<<endl;
inOrder(root->right);
}
struct node* convertToBinaryTree(const vector<int> & v, int low, int high){
if (low > high) return NULL;
//create a node for mid element
int mid = (low+high)/2;
//Deal with root.
//create a node with mid
struct node* root = insert(v[mid]);
//Trust the recursion
root->left = convertToBinaryTree(v, low, mid-1);
root->right = convertToBinaryTree(v, mid+1, high);
return root;
}
int main() {
vector<int> v = { 10, 20, 30, 40, 50};
struct node* root = convertToBinaryTree(v,0,v.size()-1);
inOrder(root);
}