方法1:
分治法;
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
/**
* 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:
ListNode* GetMid(ListNode* head)
{
if(head==NULL||head->next==NULL)
return head;
ListNode* fast=head,*slow=head,*pre=slow;
while(fast->next&&fast->next->next)
{
fast=fast->next->next;
pre=slow;
slow=slow->next;
}
if(pre==slow)
slow=slow->next;
pre->next=NULL;
return slow;
}
TreeNode* BuildTree(ListNode* head)
{
if(head==NULL)
return NULL;
if(head->next==NULL)
{
return new TreeNode(head->val);
}
ListNode* mid=GetMid(head);
TreeNode* root=new TreeNode(mid->val);
root->left=BuildTree(head);
root->right=BuildTree(mid->next);
return root;
}
TreeNode* sortedListToBST(ListNode* head) {
TreeNode* root=BuildTree(head);
return root;
}
};方法2:
先构建完全二叉树,再将链表中的数据填充到树中节点
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
/**
* 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* Build(int n)
{
TreeNode* root=NULL;
if(n==0)
return root;
n--;
root=new TreeNode(-1);
queue<TreeNode*> q;
q.push(root);
while(!q.empty())
{
TreeNode* t=q.front();
q.pop();
if(--n>=0)
{
TreeNode* left=new TreeNode(-1);
t->left=left;
q.push(left);
}
else
break;
if(--n>=0)
{
TreeNode* right=new TreeNode(-1);
t->right=right;
q.push(right);
}
}
return root;
}
void InOrder(TreeNode* root,ListNode*& head)
{
if(root==NULL)
return;
InOrder(root->left, head);
root->val=head->val;
head=head->next;
InOrder(root->right, head);
}
TreeNode* sortedListToBST(ListNode* head) {
ListNode* cur=head;
int _size=0;
while(cur)
{
_size++;
cur=cur->next;
}
TreeNode* root=Build(_size);
int cnt=0;
InOrder(root, head);
return root;
}
};
359

被折叠的 条评论
为什么被折叠?



