這道題一開始我就想錯方向了。
記得算法與數據結構中有一種數據結構是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; }};
新聞熱點
疑難解答