LeetCode:Convert Sorted Array to Binary Search Tree
Prolem:
Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
Subscribe to see which companies asked this question
Solution:
/** * 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) { return generateTree(0,nums.size()-1,nums); } TreeNode* generateTree(int left,int right,vector<int>& nums) { if(left>right) return NULL; else if(left==right) return new TreeNode(nums[left]); else { int middle=(left+right)/2; TreeNode *root=new TreeNode(nums[middle]); root->left=generateTree(left,middle-1,nums); root->right=generateTree(middle+1,right,nums); return root; } } };