您的位置:首页 > 其它

[leetcode 109] Convert Sorted List to Binary Search Tree

2015-01-14 11:34 435 查看
Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.

/**
* Definition for singly-linked list.
* struct ListNode {
*     int val;
*     ListNode *next;
*     ListNode(int x) : val(x), next(NULL) {}
* };
*/
/**
* Definition for binary tree
* struct TreeNode {
*     int val;
*     TreeNode *left;
*     TreeNode *right;
*     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode *sortedListToBST(ListNode *head) {
if (!head) {
return NULL;
}
ListNode *end = head;
while (end->next) {
end = end->next;
}
return build(head, end);

}
TreeNode *build(ListNode *begin, ListNode *end) {
if (!begin){
return NULL;
}
if (!begin->next) {
TreeNode *root = new TreeNode(begin->val);
return root;
}
ListNode dummy(-1);
dummy.next = begin;
auto slow = &dummy;
auto fast = begin;
while (fast && fast->next) {
slow = slow->next;
fast = fast->next->next;
}
TreeNode *root = new TreeNode(slow->next->val);
auto head = slow->next->next;
slow->next = NULL;
root->left = build(begin, slow);
root->right = build(head, end);
return root;

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