zoukankan      html  css  js  c++  java
  • [LeetCode] 109. Convert Sorted List to Binary Search Tree

    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

    有序链表转换二叉搜索树。

    题目即是题意,可以跟108题一起做。108是从有序数组转化成BST,109是从有序链表转化成BST。区别在于108可以通过找中点的办法快速找到根节点,但是109只能通过快慢指针的办法找到根节点,思路都是递归。

    时间O(n)

    空间O(n)

    Java实现

     1 class Solution {
     2     public TreeNode sortedListToBST(ListNode head) {
     3         if (head == null)
     4             return null;
     5         return helper(head, null);
     6     }
     7 
     8     public TreeNode helper(ListNode head, ListNode tail) {
     9         if (head == tail)
    10             return null;
    11         ListNode slow = head;
    12         ListNode fast = head;
    13         while (fast != tail && fast.next != tail) {
    14             fast = fast.next.next;
    15             slow = slow.next;
    16         }
    17         TreeNode root = new TreeNode(slow.val);
    18         root.left = helper(head, slow);
    19         root.right = helper(slow.next, tail);
    20         return root;
    21     }
    22 }

    JavaScript实现

     1 /**
     2  * @param {ListNode} head
     3  * @return {TreeNode}
     4  */
     5 var sortedListToBST = function (head) {
     6     if (head === null) return null;
     7     return helper(head, null);
     8 };
     9 
    10 var helper = function (head, tail) {
    11     if (head === tail) return null;
    12     let slow = head;
    13     let fast = head;
    14     while (fast !== tail && fast.next !== tail) {
    15         fast = fast.next.next;
    16         slow = slow.next;
    17     }
    18     let root = new TreeNode(slow.val);
    19     root.left = helper(head, slow);
    20     root.right = helper(slow.next, tail);
    21     return root;
    22 }

    相关题目

    108. Convert Sorted Array to Binary Search Tree

    109. Convert Sorted List to Binary Search Tree

    1382. Balance a Binary Search Tree

    LeetCode 题目总结

  • 相关阅读:
    JUnit4.13环境配置
    OO第5-7次作业总结
    电梯的一点浅优化
    C++变量作用域、生存期、存储类别
    最后一次OO博客
    OO第三次总结
    OO第二次总结
    OO第一次总结
    POJ3934
    POJ刷题计划
  • 原文地址:https://www.cnblogs.com/cnoodle/p/12293684.html
Copyright © 2011-2022 走看看