109. Convert Sorted List to Binary Search Tree

来源:互联网 发布:域名注册哪家便宜 编辑:程序博客网 时间:2024/06/10 04:24

Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.

解题思路:其实这是个很经典的有序链表构建二叉查找树的问题,也就是先序遍历,后序遍历,中序遍历构建的问题,三者的代码如下:

1. 先序遍历:

class Solution {private:    TreeNode *helpsortedListToBST(ListNode *head, ListNode *tail){    if( head == tail )    return NULL;    ListNode *mid = head, *temp = head;    while( temp != tail && temp->next != tail ) {    mid = mid->next;    temp = temp->next->next;    }    TreeNode *root = new TreeNode(mid->val);    root->left = helpsortedListToBST(head, mid);    root->right = helpsortedListToBST(mid->next, tail );           return root;    }public:    TreeNode *sortedListToBST(ListNode *head){    return helpsortedListToBST( head, NULL );    }};


2.中序遍历:

class Solution {private:    TreeNode *helpsortedListToBST(ListNode *head, ListNode *tail){    if( head == tail )    return NULL;    ListNode *mid = head, *temp = head;    while( temp != tail && temp->next != tail ) {    mid = mid->next;    temp = temp->next->next;    }    TreeNode *root = new TreeNode(0);    root->left = helpsortedListToBST(head, mid);        root->val = mid->val;    root->right = helpsortedListToBST(mid->next, tail );    return root;    }public:    TreeNode *sortedListToBST(ListNode *head){    return helpsortedListToBST( head, NULL );    }};


3.后续遍历:

class Solution {private:    TreeNode *helpsortedListToBST(ListNode *head, ListNode *tail){    if( head == tail )    return NULL;    ListNode *mid = head, *temp = head;    while( temp != tail && temp->next != tail ) {    mid = mid->next;    temp = temp->next->next;    }    TreeNode *root = new TreeNode(0);    root->left = helpsortedListToBST(head, mid);    root->right = helpsortedListToBST(mid->next, tail );        root->val = mid->val;    return root;    }public:    TreeNode *sortedListToBST(ListNode *head){    return helpsortedListToBST( head, NULL );    }};

其实这三者的性能是一样的,因为其实先序,中序,后序,只不过是给当前根节点的赋值的顺序罢了,结果如下:


然后就是对上面的优化,每一个递归函数里面都有一个while,循环寻找中间节点,这是很耗时间的,我们想的是如何的去掉它,去掉他,也就是我们每次不去寻找中间节点,那么不是先序遍历,只能是中序遍历和后序遍历,但是因为中序遍历的的值正好是升序,左边->中间->右边,左边<中间<右边,而链表也是升序的,也就是说中序是最简单的,正好按链表顺序构建二叉查找树;

class Solution {    private:    ListNode* ls;    TreeNode *HelpsortedListToBST(int size){    if( size == 0 ) return NULL;        TreeNode *root = new TreeNode(0);    root->left = HelpsortedListToBST( size/2 );        root->val = ls->val;        ls = ls->next;    root->right = HelpsortedListToBST( size - size/2-1 );    return root;    }public:    TreeNode *sortedListToBST(ListNode *head){        int  size = 0;        ls = head;        while( head != NULL){            head=head->next;            size++;        }    return HelpsortedListToBST(size);    }};



对比一下,性能还是提升了13%的。