Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
思路:才用快慢指针,找到中间节点,然后递归处理。
accepted code:
1 /** 2 * Definition for singly-linked list. 3 * struct ListNode { 4 * int val; 5 * ListNode *next; 6 * ListNode(int x) : val(x), next(NULL) {} 7 * }; 8 */ 9 /** 10 * Definition for a binary tree node. 11 * struct TreeNode { 12 * int val; 13 * TreeNode *left; 14 * TreeNode *right; 15 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 16 * }; 17 */ 18 class Solution { 19 public: 20 TreeNode* sortedListToBST(ListNode* head) { 21 if(head==nullptr) 22 return nullptr; 23 return toBST(head,nullptr); 24 } 25 26 TreeNode* toBST(ListNode* head,ListNode* end) 27 { 28 ListNode* slow=head; 29 ListNode* fast=head; 30 if(head==end) 31 return nullptr; 32 33 while(fast!=end&&fast->next!=end) 34 { 35 fast=fast->next->next; 36 slow=slow->next; 37 } 38 39 TreeNode* root=new TreeNode(slow->val); 40 root->left=toBST(head,slow); 41 root->right=toBST(slow->next,end); 42 return root; 43 } 44 };