标签:
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 };
【leetcode】Convert Sorted Array to Binary Search Tree
标签:
原文地址:http://www.cnblogs.com/reachteam/p/4216234.html