排序列表转换为二分查找树
2017-06-27 15:41
288 查看
开始接触链表问题。从朋友那得到指导,唤醒了以前的记忆,链表还是手动加上head比较好处理。返回的时候返回head->next比较好。此题用递归即可,快慢指针的应用,可以找到链表中点,如果不用手动加head的方法处理起来就异常艰难。
另外递归也好久没写遗忘了。写一下备忘。第一次写的时候:
slow->next = NULL; if(head != NULL) root->left = sortedListToBST(head); if(right != NULL) root->right = sortedListToBST(right); return root;
结果Runtime error了。有个问题,如果输入是0->NULL;这样的slow->next虽然为NULL,但是head不为NULL。所以还是在函数进入的时候判断链表长度是否为1,比较靠谱:
\class Solution { public: /** * @param head: The first node of linked list. * @return: a tree node */ TreeNode *sortedListToBST(ListNode *head) { // write your code here if(head == NULL) return NULL; if(head->next == NULL) return new TreeNode(head->val); ListNode *slow = new ListNode(0); slow->next = head; ListNode *fast = head; while(fast!=NULL && fast->next!=NULL){ fast = fast->next->next; slow = slow->next; } TreeNode *root = new TreeNode(slow->next->val); ListNode *right = slow->next->next; slow->next = NULL; root->left = sortedListToBST(head); root->right = sortedListToBST(right); return root; } };
相关文章推荐
- lintcode-排序列表转换为二分查找树-106
- lintcode,排序列表转换为二分查找树
- 题目:排序列表转换为二分查找树
- LINTCODE---排序列表转换为二分查找树
- 排序列表转换为二分查找树
- 排序列表转换为二分查找树-LintCode
- LintCode 排序列表转换为二分查找树
- 排序列表转换为二分查找树
- LintCode:排序列表转换为二分查找树
- 排序列表转换为二分查找树
- LintCode-排序列表转换为二分查找树分析及实例
- LintCode 106-排序列表转换为二分查找树
- 排序列表转换为二分查找树
- lintcode——排序列表转换为二分查找树(链表,二叉排序树)
- LintCode-排序列表转换为二分查找树
- lintcode-106-排序列表转换为二分查找树
- 排序列表转化为二分查找树
- lintcode- 题106 排序链表转换为二分查找树
- 游戏后台里的通用技术之二分查找和排序
- 列表--- 查找元素二分查找