Convert Sorted List to Binary Search Tree
Total Accepted: 16035 Total Submissions: 59053 My SubmissionsGiven a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
这里有两个需要注意的地方,
1-树结点的初始化,val在括号里
2-快慢指针停止是在位置,通过4,5来检测奇个结点和偶个结点时停的位置。
/**
* 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;
if (head->next == NULL) {
TreeNode *root = new TreeNode(head->val);
return root;
}
ListNode *slow = head, *fast = head->next;
while (fast->next != NULL && fast->next->next != NULL)
{
slow = slow->next;
fast = fast->next;
fast = fast->next;
}
fast = slow->next;
slow->next = NULL;
TreeNode *root = new TreeNode(fast->val);//
fast = fast->next;
TreeNode *left = sortedListToBST(head);
TreeNode *right = sortedListToBST(fast);
root->left = left;
root->right = right;
return root;
}
};