题目:
Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
题目来源:https://oj.leetcode.com/problems/convert-sorted-list-to-binary-search-tree/
解题思路:先遍历一遍链表,把链表值存入vector中,然后再调用上面一题中所提交的方法。
上一题连接:http://blog.csdn.net/u010585135/article/details/40892567
#include<iostream>
#include<vector>
using namespace std;
struct ListNode
{
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
struct TreeNode
{
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
void sortedArrayToBST(TreeNode *root,vector<int> &num,int first,int mid,int last)
{
if(first>=last)
return ;
if(first<mid)//说明可以有左子树
{
root->left=new TreeNode(num[first+((mid-first)>>1)]);
sortedArrayToBST(root->left,num,first,first+((mid-first)>>1),mid-1);
}
if(last>mid)//说明可以有右子树
{
root->right=new TreeNode(num[mid+1+((last-mid)>>1)]);
sortedArrayToBST(root->right,num,mid+1,mid+1+((last-mid)>>1),last);
}
}
TreeNode *sortedArrayToBST(vector<int> &num)
{
if(num.empty())
return NULL;
TreeNode *root=new TreeNode(num[(num.size()-1)>>1]);
sortedArrayToBST(root,num,0,(num.size()-1)>>1,num.size()-1);
return root;
}
TreeNode *sortedListToBST(ListNode *head)
{
if(head==NULL)
return NULL;
ListNode *curr=head;
vector<int> num;
for(int i=0;curr!=NULL;i++)
{
num.push_back(curr->val);
curr=curr->next;
}
return sortedArrayToBST(num);
}
int main()
{
ListNode *head=new ListNode(1);
ListNode *curr=head;
for(int i=2;i<=7;i++)
{
curr->next=new ListNode(i);
curr=curr->next;
}
TreeNode *root=sortedListToBST(head);
system("pause");
return 0;
}