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

    /**
     * 109. Convert Sorted List to Binary Search Tree
     * 1. Time:O(nlogn)  Space:O(logn)
     * 2. Time:O(n)  Space:O(logn)
     */
    
    // 1. Time:O(nlogn)  Space:O(logn)
    class Solution {
        public TreeNode sortedListToBST(ListNode head) {
            if(head == null) return null;
            ListNode mid = midNode(head);
            TreeNode root = new TreeNode(mid.val);
            if(head==mid)
                return root;
            root.left = sortedListToBST(head);
            root.right = sortedListToBST(mid.next);
            return root;
        }
        
        private ListNode midNode(ListNode head){
            ListNode prev = null;
            ListNode slow = head;
            ListNode fast = head;
            while(fast!=null && fast.next!=null){
                prev = slow;
                slow = slow.next;
                fast = fast.next.next;
            }
            if(prev!=null)
                prev.next = null;
            return slow;
        }
    }
    
    // 2. Time:O(n)  Space:O(logn)
    class Solution {
        
        private ListNode head;
        
        public TreeNode sortedListToBST(ListNode head) {
            int len = listLen(head);
            this.head = head;
            return helper(0,len-1);
        }
        
        private TreeNode helper(int start, int end){
            if(start>end) return null;
            int mid = (start+end) >>> 1;
            TreeNode left = helper(start,mid-1);
            TreeNode root = new TreeNode(this.head.val);
            root.left = left;
            this.head = this.head.next;
            TreeNode right = helper(mid+1,end);
            root.right = right;
            return root;
        }
        
        private int listLen(ListNode head){
            ListNode cur = head;
            int len = 0;
            while(cur!=null){
                cur = cur.next;
                len++;
            }
            return len;
        }
    }
    
  • 相关阅读:
    正则表达式语法学习
    微软开放WP开发者回复用户应用评论功能
    下载安全程序需谨慎 黑客盯上XP用户
    软件业进入由大变强关键期
    54%的恶意程序无法被检测出
    CSS:第1课
    Javascript疑问【长期更新】
    不同语言的注释【长期更新】
    定制博客CSS样式
    认识Html DOM
  • 原文地址:https://www.cnblogs.com/AAAmsl/p/12842057.html
Copyright © 2011-2022 走看看