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
57
58
59


#include <vector>
#include <iostream>

using namespace std;
struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};

//generate BST from elements of num in range [low, high)
TreeNode *sortedArrayToBST(vector<int> &num, int low, int high) {
    if (low >= high) return NULL;
    
    int mid = (high-low)/2 + low;
    TreeNode *n = new TreeNode(num[mid]);
    
    n->left = sortedArrayToBST(num, low, mid);
    n->right = sortedArrayToBST(num, mid+1, high);
    
    return n;
}

TreeNode *sortedArrayToBST(vector<int> &num) {
    return sortedArrayToBST(num, 0, num.size());
}

void preorderPrintTree(TreeNode *n) {
    if (n == NULL) {
        cout << "#, ";
        return;
    }
    
    cout << n->val << ", ";
    preorderPrintTree(n->left);
    preorderPrintTree(n->right);
}

int main (int argc, const char * argv[]) {
    
    int a[] = {0,1,2};
    vector<int> va(a, a+sizeof(a)/sizeof(int));
    preorderPrintTree(sortedArrayToBST(va));
    cout << endl;
    
    int b[] = {0,1,2,3,4,5,6,7,8,9};
    vector<int> vb(b, b+sizeof(b)/sizeof(int));
    preorderPrintTree(sortedArrayToBST(vb));
    cout << endl;
    return 0;
}


// Output:
// 1, 0, #, #, 2, #, #, 
// 5, 2, 1, 0, #, #, #, 4, 3, #, #, #, 8, 7, 6, #, #, #, 9, #, #, 
View Program Text


Test Status