这道题一开始我就想错方向了。
记得算法与数据结构中有一种数据结构是AVL树,AVL不考虑插入的数字是否排列有序。
本题中用到的思想有 快慢指针 递归(涉及到树的操作大多是递归)
代码如下:
class Solution {public:    TreeNode* sortedListToBST(ListNode* head) {        if(!head) return NULL;        if(!head->next) return new TreeNode(head->val);        ListNode* fast=head->next;        ListNode* slow=head;        while(fast->next&&fast->next->next)        {            fast=fast->next->next;            slow=slow->next;        }        ListNode* mid=slow->next;        slow->next=NULL;        TreeNode* ret=new TreeNode(mid->val);        ret->left=sortedListToBST(head);        ret->right=sortedListToBST(mid->next);        return ret;    }};
新闻热点
疑难解答