您的位置:首页 > 其它

Leetcode 109. Convert Sorted List to Binary Search Tree

2018-02-08 09:12 387 查看
原题:
Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees ofevery node never differ by more than 1.

Example:Given the sorted linked list: [-10,-3,0,5,9],

One possible answer is: [0,-3,9,-10,null,5], which represents the following height balanced BST:

0
/ \
-3 9
/ /
-10 5

解决方法:
用快慢指针的方法将链表分成前后两部分,前面的做为左子节点,后面的做为右子节点。

代码:
TreeNode* sortedListToBST(ListNode* head) {
if (!head)
return NULL;

if (!head->next)
return new TreeNode(head->val);

ListNode* slow = head, *fast = head->next->next;
while(fast && fast->next){
slow = slow->next;
fast = fast->next->next;
}

ListNode* cur = slow->next, *right = slow->next->next;
slow->next = NULL;
TreeNode* root = new TreeNode(cur->val);
root->left = sortedListToBST(head);
root->right = sortedListToBST(right);
return root;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  cplusplus Leetcode