【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.
每次把中间元素当成根节点,递归即可
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 TreeNode *sortedArrayToBST(vector<int> &num) { 13 14 TreeNode *root=buildTree(num,0,num.size()-1); 15 return root; 16 } 17 18 19 TreeNode *buildTree(vector<int> &num,int l,int r) 20 { 21 if(l>r) return NULL; 22 23 int mid=(l+r)/2; 24 25 TreeNode *root=new TreeNode(num[mid]); 26 root->left=buildTree(num,l,mid-1); 27 root->right=buildTree(num,mid+1,r); 28 29 return root; 30 } 31 };