Convert Sorted List to Binary Search Tree

来源:互联网 发布:mac os x 10.12.6镜像 编辑:程序博客网 时间:2024/06/16 03:50
Problem:
Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.

递归求解,Solution1是原创版本,先序遍历,时间复杂度nlog(n)。Solution2是讨论区大牛版本,中序遍历,时间复杂度n。
Solution1:
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; next = null; }
 * }
 */
/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public TreeNode sortedListToBST(ListNode head) {
        if(head==null)
             return null;
        
        int cnt = 0;
        ListNode p = head;
        while(p!=null)
        {
             p = p.next;
             cnt++;
        }
        return subBST(head, cnt);
    }
    
    private TreeNode subBST(ListNode head, int len)
    {
         if(len==1)
             return new TreeNode(head.val);
         TreeNode root;
         if(len==2)
         {
             root = new TreeNode(head.next.val);
             root.left = new TreeNode(head.val);
             return root;
          }
    
          int cnt = 0;
          ListNode p = head;
          while(cnt<len/2)
         {
             p = p.next;
             cnt++;
         }
    
          root = new TreeNode(p.val);
          root.left = subBST(head, len/2);
          root.right = subBST(p.next, (len-1)/2);
          return root;
    }
}


Solution2:
class Solution {
public:
    ListNode *list;
    int count(ListNode *node){
        int size = 0;
        while (node) {
            ++size;
            node = node->next;
        }
        return size;
    }


    TreeNode *generate(int n){
        if (n == 0)
            return NULL;
        TreeNode *node = new TreeNode(0);
        node->left = generate(n / 2);
        node->val = list->val;
        list = list->next;
        node->right = generate(n - n / 2 - 1);
        return node;
    }


    TreeNode *sortedListToBST(ListNode *head) {
        this->list = head;
        return generate(count(head));
    }
};

0 0
原创粉丝点击