您的位置:首页 > 其它

排序列表转换为二分查找树

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;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: