您的位置:首页 > 其它

Convert Sorted List to Binary Search Tree

2014-08-24 11:05 267 查看


Convert Sorted List to Binary Search Tree



Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.


TreeNode *sortedListToBST(ListNode *head) {
return sortedListToBST(head,listLength(head));
}

TreeNode* sortedListToBST(ListNode* head,int len)
{
if(len ==0) return nullptr;
if(len ==1) return new TreeNode(head->val);
TreeNode* root =new TreeNode(nth_node(head,len/2+1)->val);
root->left =sortedListToBST(head,len/2);
root->right =sortedListToBST(nth_node(head,len/2+2),(len-1)/2);
return root;
}

int listLength(ListNode* node)
{
int n=0;
while(node)
{
++n;
node =node->next;
}
return n;
}

ListNode* nth_node(ListNode* node,int n)
{
while(--n)
{
node =node->next;
}
return node;
}


 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  二叉树 Leetcode 链表