leetcode Convert Sorted List to Binary Search Tree

来源:互联网 发布:网络电视iptv设置 编辑:程序博客网 时间:2024/05/16 08:16

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;}}


原创粉丝点击