leetcode - Convert Sorted Array to Binary Search Tree
2013-03-28 10:12 张汉生 阅读(142) 评论(0) 编辑 收藏 举报题目描述:点击此处
1 /** 2 * Definition for binary tree 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution { 11 public: 12 typedef vector<int>::iterator vi; 13 TreeNode *sortedArrayToBST(vi begin, vi end){ 14 if (begin==end) 15 return NULL; 16 vi middle = begin + (end-begin)/2; 17 TreeNode * root = new TreeNode(*middle); 18 root->left = sortedArrayToBST(begin,middle); 19 root->right = sortedArrayToBST(middle+1,end); 20 return root; 21 } 22 TreeNode *sortedArrayToBST(vector<int> &num) { 23 // Start typing your C/C++ solution below 24 // DO NOT write int main() function 25 if (num.empty()) 26 return NULL; 27 return sortedArrayToBST(num.begin(),num.end()); 28 } 29 };