您的位置:首页 > 其它

LeetCode:Convert Sorted List to Binary Search Tree

2016-04-14 16:36 465 查看


Convert Sorted List to Binary Search Tree

Total Accepted: 67959 Total
Submissions: 224265 Difficulty: Medium

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

Subscribe to see which companies asked this question

Hide Tags
 Depth-first Search Linked
List

Hide Similar Problems
 (M) Convert Sorted Array to Binary Search Tree

code:

/**
* 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* sortedListToBST(ListNode* head) {
return sortedListToBST(head, NULL);
}

TreeNode* sortedListToBST(ListNode* head, ListNode *tail) {

if(head == tail) return NULL;

ListNode *fast = head,*slow = head;
while(fast!=tail && fast->next != tail){ // 找到中间结点
fast = fast->next->next;
slow = slow->next;
}
TreeNode *root = new TreeNode(slow->val);
root->left = sortedListToBST(head, slow);
root->right = sortedListToBST(slow->next, tail);
return root;
}

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