leetcode Convert Sorted List to Binary Search Tree

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


C++ is getting this problem more clear. you don't have random access to the list. so try doing it recursively while modifying the pointer. If in Java, we'll have to keep a global variable.


/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    TreeNode *sortedListToBST(ListNode *head) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        ListNode *tmp=head;
        int size=0;
        while(tmp){
            size++;
            tmp=tmp->next;
        }
        return get(&head,size);
    }
    TreeNode *get(ListNode **head, int size) {
        if(size<=0) return NULL;
        int i=size/2;
        TreeNode* l=get(head,i);
        TreeNode *x=new TreeNode((*head)->val);
        *head=(*head)->next;
        x->left=l;
        x->right=get(head,size-i-1);
        return x;}
};


java version

public class Solution {
    public TreeNode sortedListToBST(ListNode head) {
        // Start typing your Java solution below
        // DO NOT write main() function
        ListNode tmp=head;
        int i=0;
        while(tmp!=null){
            i++;
            tmp=tmp.next;
        }
        ListNode a[]=new ListNode[1];//since java doesn't have pointer, we need a global variable or something that contains the object
        a[0]=head;
        return build(i,a);
        
    }
    
    public TreeNode build(int size,ListNode head[]) {
        
        if(size<=0) return null;
        TreeNode l=build(size/2,head);
        TreeNode c=new TreeNode(head[0].val);
        c.left=l;
        head[0]=head[0].next;
        c.right=build(size-size/2-1,head);
    
        return c;}
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值