• 【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.

    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层

    public class Solution {
        public TreeNode sortedListToBST(ListNode head) {
            TreeNode no = BuildBST(head,null);
            return no;
            
        }
    
        private TreeNode BuildBST(ListNode start, ListNode end) {
            if(start==end)
                return null;
            ListNode slow = start;
            ListNode fast = start;
            
            while(fast!=end&&fast.next!=end){
                
                slow=slow.next;
                fast=fast.next.next;
            }
            TreeNode root = new TreeNode(slow.val);
            root.left=BuildBST(start,slow);
            root.right=BuildBST(slow.next,end);
            return root;
            
        }
    }

    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 }
  • 相关阅读:
    PHP把下划线分隔命名的字符串与驼峰式命名互转
    Cocos2d-JS/Ajax用Protobuf与NodeJS/Java通信
    gulp 实现 js、css,img 合并和压缩
    转:入门Webpack,看这篇就够了
    微信开发教程:用户账号绑定到微信公众号的方法分享
    C#RSA算法实现+如何将公钥为XML格式转为PEM格式,给object-C使用
    php使用openssl进行Rsa长数据加密(117)解密(128) 和 DES 加密解密
    Windows下将nginx安装为服务运行
    转载:Centos7 从零编译配置Memcached
    转载:Centos7 从零编译Nginx+PHP+MySql 二
  • 原文地址:https://www.cnblogs.com/yixianyixian/p/3721095.html
Copyright © 2020-2023  润新知