【Leetcode】Convert Sorted List to Binary Search Tree

来源:互联网 发布:淘宝详情模板代码 编辑:程序博客网 时间:2024/04/30 08:51

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


【思路】这道题目就和array不一样,因为是linkedlist所以,不能随意访问到中间的元素,那么就只能一步一步从头开始顺序访问,从列表到BST,我们能感受到构造的规律,所以这次通过定出list, bottom-up来构造起树。

间接了大神的分析:

 constructing the tree from leaves to root,to do that insert nodes in BST in the same order as the appear in Linked List, by doing so the time complexity would be simply O(n) as we just need to traverse the linked list.

STEP 1: Take left n/2 nodes and recursively construct the left sub tree.

STEP 2: After left sub tree is constructed, we allocate memory for root and link the left sub tree with root.

STEP 3: Finally, we recursively construct the right sub tree and link it with root.

NOTE :: While constructing the BST, we also keep moving the list head pointer to next so that we have the appropriate pointer in each recursive call.

这也算是inorder traversal了吧!

【代码】

public class Solution {    private ListNode cur;    public TreeNode sortedListToBST(ListNode head) {        cur = head;        return generate(count(head));    }    private TreeNode generate(int n){        if (0 == n)            return null;        TreeNode node = new TreeNode(0);        node.left = generate(n/2);        node.val = cur.val;        cur = cur.next;        node.right = generate(n-n/2-1);        return node;    }    private int count(ListNode h){        int size = 0;        while (h != null){            ++size;            h = h.next;        }        return size;    }}

0 0