Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
其实挺难的,一次写对更难。 这种sorted array/list to balanced tree的题目就是递归的找中间然后左右继续
linked list不一样的地方是每次找中间有个小trick,然后就是判断是不是leaf得时候,array用的start==end,这里其实start->next==end。这样的好处是不把mid包括进去,方便遍历的时候以mid为左面终点,和mid->next为右树的起点。。。。
/**
* 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) {
return helper(head, 0);
}
TreeNode* helper(ListNode* head, ListNode* tail){
if (head==tail)
return 0;
if (head->next==tail)
return new TreeNode(head->val);
ListNode *tmp=head, *mid=head;
while(tmp!=tail && tmp->next!=tail){
mid=mid->next;
tmp=tmp->next->next;
}
TreeNode* root=new TreeNode(mid->val);
root->left=helper(head,mid);
root->right=helper(mid->next,tail);
return root;
}
};
363

被折叠的 条评论
为什么被折叠?



