Convert Sorted Array to Binary Search Tree
Convert Sorted Array to Binary Search Tree
Total Accepted: 61516 Total Submissions: 173462 Difficulty: Medium
Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: TreeNode* sortedArrayToBST(vector<int>& nums,int start,int end){ if(end <= start) return NULL; int mid = start + (end-start)/2; TreeNode* root = new TreeNode(nums[mid]); root->left = sortedArrayToBST(nums,start,mid); root->right = sortedArrayToBST(nums,mid+1,end); return root; } TreeNode* sortedArrayToBST(vector<int>& nums) { int nums_size = nums.size(); return sortedArrayToBST(nums,0,nums_size); } };
写者:zengzy
出处: http://www.cnblogs.com/zengzy
标题有【转】字样的文章从别的地方转过来的,否则为个人学习笔记