zoukankan      html  css  js  c++  java
  • 由有序链表构建平衡二叉搜索树-sortedListToBST

    描述

    • 给定一个有序列表,将其转换成为一个平衡搜索二叉树
    • 题不难,不过在讨论中发现此题的中序遍历用法略有不同,感觉有点意思
    • 手写一遍加深印象
    • 暴力解法,链表转数组,额外空间O(N),递归遍历搞定。几分钟解决,但显然不是最优。
    • 其次思考类似于红黑树进行节点旋转,后来发现成本较高。
    • 到讨论区发现solution-2的解法:计数得到节点总数,知道节点数就可以确定一种满足要求的BST结构,然后使用中序遍历,将列表元素填入BST对应节点。

    Description

    109. Convert Sorted List to Binary Search Tree
    Medium
    
    2382
    
    90
    
    Add to List
    
    Share
    Given the head of a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
    
    For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
    
    
    
    Example 1:
    
    
    Input: head = [-10,-3,0,5,9]
    Output: [0,-3,9,-10,null,5]
    Explanation: One possible answer is [0,-3,9,-10,null,5], which represents the shown height balanced BST.
    
    Example 2:
    
    Input: head = []
    Output: []
    
    Example 3:
    
    Input: head = [0]
    Output: [0]
    
    Example 4:
    
    Input: head = [1,3]
    Output: [3,1]
    
    
    Constraints:
    
    The number of nodes in head is in the range [0, 2 * 104].
    -10^5 <= Node.val <= 10^5
    

    Solution-1

    • traversal the list and add all elements into a array
    • then convert this problem to 108_convert_sorted_array_to_binary_search_tree.
    • time cost : O(N) + O(N) + O(N) ~ O(N) : traversal the list + recursive construct tree + read the elements in list
    • space cost : O(N) + O(logN) ~ O(N) : array space and recursive stack cost.
    AC Result
    • Runtime: 132 ms, faster than 47.94% of Python online submissions for Convert Sorted List to Binary Search Tree.
    • Memory Usage: 25.5 MB, less than 21.90% of Python online submissions for Convert Sorted List to Binary Search Tree.
    show me the code
        def sortedArrayToBST(self, nums):
            """
            :type nums: List[int]
            :rtype: TreeNode
            Runtime: 52 ms, faster than 99.19% of Python online submissions for Convert Sorted Array to Binary Search Tree.
            Memory Usage: 17 MB, less than 35.16% of Python online submissions for Convert Sorted Array to Binary Search Tree.
            """
            nums_len = len(nums)
            if(nums_len == 0):
                return None
            if(nums_len == 1):
                return TreeNode(nums[0])
            mid = nums_len / 2
            root = TreeNode(nums[mid])
            root.left = self.sortedArrayToBST(nums[0:mid])
            root.right = self.sortedArrayToBST(nums[mid + 1 :])
            return root
    
        def sortedListToBST(self, head):
            """
            :type head: ListNode
            :rtype: TreeNode
            Runtime: 132 ms, faster than 47.94% of Python online submissions for Convert Sorted List to Binary Search Tree.
            Memory Usage: 25.5 MB, less than 21.90% of Python online submissions for Convert Sorted List to Binary Search Tree.
            """
            head_arr = []
            cur_point = head
            while(cur_point):
                head_arr.append(cur_point.val)
                cur_point = cur_point.next
            return self.sortedArrayToBST(head_arr)
    

    Solution-2

    • inorder Traversal to fill all elements in list in a new tree construct by recursive.
      how to understand this solution:
    1. we count all elements in list so that we can know the tree constructure which corresponds the conditions of BST
    2. inorder traversal the specified BST
    3. fill the elements in list into the target tree.
      this is mean we traversal the tree by inorder function, fill the sorted elements at specified positions.
    • time cost : O(N) + O(N) + O(N) ~ O(N) : traversal the list + recursive construct tree + read the elements in list

    • space cost : O(1) + O(logN) ~ O(logN) : recursive stack cost.

    AC Result
    • Runtime: 124 ms, faster than 80.95% of Python online submissions for Convert Sorted List to Binary Search Tree.
    • Memory Usage: 25.7 MB, less than 21.90% of Python online submissions for Convert Sorted List to Binary Search Tree.
    show me the code
    
        def sortedListToBST(self, head):
            if(None == head):
                return None
            cur_point = head
            head_count = 0
            while(cur_point):
                head_count += 1
                cur_point = cur_point.next
            self.cur_point = head
            return self.inner_sorted_list_to_bst(1, head_count)
    
        def inner_sorted_list_to_bst(self, start_idx, end_idx):
            '''
            inorder Traversal to fill all elements in list in a new tree construct by recursive.
            how to understand this solution:
            1. we count all elements in list so that we can know the tree constructure which corresponds the conditions of BST
            2. inorder traversal the specified BST
            3. fill the elements in list into the target tree.
            this is mean we traversal the tree by inorder function, fill the sorted elements at specified positions.
            Runtime: 124 ms, faster than 80.95% of Python online submissions for Convert Sorted List to Binary Search Tree.
            Memory Usage: 25.7 MB, less than 21.90% of Python online submissions for Convert Sorted List to Binary Search Tree.
            :param start_idx:
            :param end_idx:
            :return:
            '''
            if(start_idx > end_idx):
                return None
            mid_idx = start_idx + (end_idx - start_idx)/2
            left = self.inner_sorted_list_to_bst(start_idx, mid_idx -1)
            root = TreeNode(self.cur_point.val)
            root.left = left
            self.cur_point = self.cur_point.next
            root.right = self.inner_sorted_list_to_bst(mid_idx +1 , end_idx)
            return root
    
  • 相关阅读:
    Android 工程师进阶 34 讲
    300分钟搞定数据结构与算法
    即学即用的Spark实战44讲
    42讲轻松通关 Flink
    Webpack原理与实践
    大数据运维实战
    ZooKeeper源码分析与实战
    前端高手进阶
    重学数据结构与算法
    ElementUI中el-upload怎样上传文件并且传递额外参数给Springboot后台进行接收
  • 原文地址:https://www.cnblogs.com/suanec/p/13866112.html
Copyright © 2011-2022 走看看