LeetCode Convert Sorted List to Binary Search Tree

来源:互联网 发布:农村淘宝怎么取消绑定 编辑:程序博客网 时间:2024/06/06 03:15

这题刚开始的做法是把链表中的元素放到数组,然后按照上一题的做法,结果出现内存不够用而通不过,再想想,和上题相似,对链表递归操作,每次找到中间位置就行了,只不过时间复杂度增加了点,但对于链表这不可避免的。如下:

TreeNode *resusiveListToBST(ListNode *head,int num) {if(head==NULL||num<=0)return NULL;TreeNode *tp;if (num==1){tp = new TreeNode(head->val);return tp;}int half = num/2;ListNode *lp=head;while(half){half--;lp = lp->next;}tp = new TreeNode(lp->val);tp->left = resusiveListToBST(head,num/2);tp->right = resusiveListToBST(lp->next,num - num/2 - 1);return tp;}TreeNode *sortedListToBST(ListNode *head) {if(head==NULL)return NULL;int lennum=0;ListNode *lp=head;while(lp){lennum++;lp = lp->next;}return resusiveListToBST(head,lennum);}


0 0