Leetcode 109. Convert Sorted List to Binary Search Tree

来源:互联网 发布:兰州ps软件班 编辑:程序博客网 时间:2024/05/17 08:28

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

s思路:
1. Leetcode 108. Convert Sorted Array to Binary Search Tree的变形。这回不用vector,改用list。两者有什么区别吗?链表要访问中间某个节点需要从头一个一个移动到所要找的位置,即:查询的复杂度o(n),而vector的查询可以一步到位o(1)。因此,不能通过计算中点的方法来做,试试用iterative,从左往右遍历list。
2. 参考了https://discuss.leetcode.com/topic/3286/share-my-code-with-o-n-time-and-o-1-space 对list用iterative,对BST还用recursive. 按照以上链接的说法:对bst用in-order遍历,由于list就是inorder的顺序,那么bst inorder就和list刚好match。具体说:先知道list长度,然后按照inorder遍历的方式构造左子树,中间节点,右子树。
3. 由于每个节点只访问一次,故o(n)。这道题,技巧性比较强。但是把list和tree放在一起,还是不错!

class Solution {//private:    //ListNode* head;//注意:用reference的效果和用private变量的作用一样    //需要在所有recursive调用过程中改变一个变量,即这个变量是全局变量!public:    int number(ListNode* head){        int count=0;        while(head){            count++;            head=head->next;            }           return count;    }    TreeNode* helper(int n,ListNode* &head){//bug:ListNode& *head,复习一下,ListNode*是一种数据类型,所以应该用ListNode* &表示是(ListNode*)的reference!        if(n==0) return NULL;        TreeNode* cur=new TreeNode(0);//先建一个空树,        cur->left=helper(n/2,head);//先访问左边,        cur->val=head->val;//再访问中间,赋值,        head=head->next;//赋值后,移动list        cur->right=helper(n-n/2-1,head);//最后访问右边        return cur;    }       TreeNode* sortedListToBST(ListNode* head) {        //this->head=head;        return helper(number(head),head);    }};
0 0
原创粉丝点击