• Convert Sorted List to Binary Search Tree


    https://leetcode.com/problems/convert-sorted-list-to-binary-search-tree/#/description

    跟数组那题没有什么本质区别,唯一的障碍是,在数组里因为长度已知,所以求中位数很方便。但是链表里找中位数就麻烦一点了。

    快慢指针再一次登场了,快指针一次走两步,慢指针一次走一步。那么当快指针走到尽头的时候,慢指针就刚好指在链表的中间。

    function ListNode(val) {
         this.val = val;
         this.next = null;
     }
    
    function TreeNode(val) {
        this.val = val;
        this.left = this.right = null;
    }
    
    /**
     * @param {ListNode} head
     * @return {TreeNode}
     */
    var sortedListToBST = function(head) {
    
        return ct(head, null);    
    };
    
    function ct(head, tail) {
        if (!head) return null;
        if (head == tail) {return null;}
    
        var mid = head;
        var fast = head;
        while (fast.next !== tail && fast.next.next !== tail) {
            mid  = mid.next;
            fast = fast.next.next;
        }
        var root = new TreeNode(mid.val);
        root.left = ct(head, mid);
        root.right = ct(mid.next, tail);
        return root;
    }
    
    
  • 相关阅读:
    hdu 1106 排序(排序)
    hdu 1040 As Easy As A+B(排序)
    hdu 1029 Ignatius and the Princess IV(排序)
    mysql-9索引
    mysql-8 alter命令
    mysql-7事务管理
    mysql-6正则表达式
    http协议
    9-2交互体验
    9-2专项测试下午
  • 原文地址:https://www.cnblogs.com/agentgamer/p/6963372.html
Copyright © 2020-2023  润新知