zoukankan      html  css  js  c++  java
  • 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.

    Top down 的解题方法:

    1. 将LinkedList的值保存到一个数组中,转化成Convert Sorted Array to Binary Search Tree 来解决

    时间复杂度为O(n), 空间复杂度为O(n)

     1 /**
     2  * Definition for singly-linked list.
     3  * public class ListNode {
     4  *     int val;
     5  *     ListNode next;
     6  *     ListNode(int x) { val = x; next = null; }
     7  * }
     8  */
     9 /**
    10  * Definition for binary tree
    11  * public class TreeNode {
    12  *     int val;
    13  *     TreeNode left;
    14  *     TreeNode right;
    15  *     TreeNode(int x) { val = x; }
    16  * }
    17  */
    18 public class Solution {
    19     public TreeNode sortedListToBST(ListNode head) {
    20         // Start typing your Java solution below
    21         // DO NOT write main() function
    22         if(head == null){
    23             return null;
    24         }
    25         int len = 0;
    26         ListNode p = head;
    27         while(p != null){
    28             len ++;
    29             p = p.next;
    30         }
    31         int[] num = new int[len];
    32         p = head;
    33         int i = 0;
    34         while(p != null){
    35             num[i++] = p.val;
    36             p = p.next;
    37         }
    38         
    39         return generate(num, 0, len - 1);
    40     }
    41     
    42     public TreeNode generate(int[] num, int start, int end){
    43         if(start > end){
    44             return null;
    45         }
    46         int mid = (start + end) / 2;
    47         TreeNode root = new TreeNode(num[mid]);
    48         root.left = generate(num, start, mid - 1);
    49         root.right = generate(num, mid + 1, end);
    50         return root;
    51     }
    52 }

    2. 使用上题的解题思路:

    遍历链表,找到中间元素,将该元素作为根节点时间复杂度为O(NlgN)

    因为每层的递归调用需要遍历N/2个元素,而一共有lgN层

     1 /**
     2  * Definition for singly-linked list.
     3  * public class ListNode {
     4  *     int val;
     5  *     ListNode next;
     6  *     ListNode(int x) { val = x; next = null; }
     7  * }
     8  */
     9 /**
    10  * Definition for binary tree
    11  * public class TreeNode {
    12  *     int val;
    13  *     TreeNode left;
    14  *     TreeNode right;
    15  *     TreeNode(int x) { val = x; }
    16  * }
    17  */
    18 public class Solution {
    19     public TreeNode sortedListToBST(ListNode head) {
    20         // Start typing your Java solution below
    21         // DO NOT write main() function
    22         if(head == null){
    23             return null;
    24         }
    25         int len = 0;
    26         ListNode p = head;
    27         while(p != null){
    28             len ++;
    29             p = p.next;
    30         }
    31         return generate(head, len);
    32     }
    33     
    34     public TreeNode generate(ListNode head, int N){
    35         if(N <= 0){
    36             return null;
    37         }
    38         int mid = (1 + N) / 2;
    39         ListNode p = head;
    40         int tmp = mid - 1;
    41         while(tmp > 0){
    42             p = p.next;
    43             tmp --;
    44         }
    45         TreeNode root = new TreeNode(p.val);
    46         root.left = generate(head, mid - 1);
    47         root.right = generate(p.next, N - mid);
    48         return root;
    49     }
    50     
    51 }

    Best Solution:
    As usual, the best solution requires you to think from another perspective. In other words, we no longer create nodes in the tree using the top-down approach. We create nodes bottom-up, and assign them to its parents. The bottom-up approach enables us to access the list in its order while creating nodes.

    Isn’t the bottom-up approach neat? Each time you are stucked with the top-down approach, give bottom-up a try. Although bottom-up approach is not the most natural way we think, it is extremely helpful in some cases. However, you should prefer top-down instead of bottom-up in general, since the latter is more difficult to verify in correctness.

    Below is the code for converting a singly linked list to a balanced BST. Please note that the algorithm requires the list’s length to be passed in as the function’s parameters. The list’s length could be found in O(N) time by traversing the entire list’s once. The recursive calls traverse the list and create tree’s nodes by the list’s order, which also takes O(N) time. Therefore, the overall run time complexity is still O(N).

     1 BinaryTree* sortedListToBST(ListNode *& list, int start, int end) {
     2   if (start > end) return NULL;
     3   // same as (start+end)/2, avoids overflow
     4   int mid = start + (end - start) / 2;
     5   BinaryTree *leftChild = sortedListToBST(list, start, mid-1);
     6   BinaryTree *parent = new BinaryTree(list->data);
     7   parent->left = leftChild;
     8   list = list->next;
     9   parent->right = sortedListToBST(list, mid+1, end);
    10   return parent;
    11 }
    12  
    13 BinaryTree* sortedListToBST(ListNode *head, int n) {
    14   return sortedListToBST(head, 0, n-1);
    15 }
  • 相关阅读:
    logback 常用配置详解(二) <appender>
    logback 配置详解(一)
    logstash报错如下:Validation Failed: 1: this action would add [2] total shards, but this cluster currently has [999]/[1000] maximum shards open
    从字节码角度分析Byte类型变量b++和++b
    接口和抽象类有什么区别?你选择使用接口和抽象类的依据是什么?
    计算1至n中数字X出现的次数
    转:轻松搞定面试中的红黑树问题
    转:40个Java集合面试问题和答案
    自定义Adapter为什么会重复多轮调用getView?——原来是ListView.onMeasure在作祟
    何时调用getView?——从源码的角度给出解答
  • 原文地址:https://www.cnblogs.com/feiling/p/3267917.html
Copyright © 2011-2022 走看看