问题:
Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
思路:先遍历一遍链表,将值存入一个vector中,再讲vector中有序数据构建平衡二叉搜索树。
代码:
1 TreeNode* sortedListToBST(ListNode* head) 2 { 3 vector<int> nums; 4 while(head!=NULL) 5 { 6 nums.push_back(head->val); 7 head=head->next; 8 } 9 return solve(nums,0,nums.size()-1); 10 } 11 12 TreeNode* solve(vector<int>& nums,int low,int high) 13 { 14 if (low>high) 15 return NULL; 16 int mid=(low+high)/2; 17 TreeNode* root=new TreeNode(nums[mid]); 18 19 root->left=solve(nums,low,mid-1); 20 root->right=solve(nums,mid+1,high); 21 22 return root; 23 }
109.Convert Sorted List to Binary Search Tree
原文:http://www.cnblogs.com/zhang-hill/p/5106029.html