[LeetCode]Convert Sorted Array to Binary Search Tree
Convert Sorted Array to Binary Search Tree
Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
BST的规则就是左<根<右,所有这道题和二分搜索差不多。
注意处理的细节,是的无论奇数个num还是偶数个num都适用。
适用递归实现。
1 /** 2 * Definition for a binary tree node. 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 TreeNode* sortedArrayToBST(vector<int>& nums) { 13 return createTree(nums,0,nums.size()-1); 14 } 15 TreeNode* createTree(vector<int>& nums,int left,int right) 16 { 17 if(left>right) return NULL; 18 int mid = (left+right)/2; 19 TreeNode* leftTree = createTree(nums,left,mid-1); 20 TreeNode* rightTree = createTree(nums,mid+1,right); 21 TreeNode* root = new TreeNode(nums[mid]); 22 root->left = leftTree; 23 root->right = rightTree; 24 return root; 25 } 26 };