【Leetcode】Convert Sorted List to Binary Search Tree

46 篇文章 0 订阅
16 篇文章 0 订阅

【题目】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;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值