#include <iostream> #include <vector> using namespace std; struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; class Solution { public: TreeNode* createbst(vector<int> &a, int lhs, int rhs) { if(lhs <= rhs) { int mid = (lhs + rhs) >> 1; TreeNode *root = new TreeNode(a[mid]); root->left = createbst(a, lhs, mid-1); root->right = createbst(a, mid+1, rhs); return root; } return 0; } TreeNode *sortedArrayToBST(vector<int> &num) { int len = num.size(); return createbst(num, 0, len - 1); } void print(TreeNode *root) { if(!root) return; else { print(root->left); cout << root->val << endl; print(root->right); } } }; int main(void) { int a[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 }; int len = sizeof(a) / sizeof(int); vector<int> v(a, a + len); Solution s; TreeNode* p = s.sortedArrayToBST(v); s.print(p); return 0; }