zoukankan      html  css  js  c++  java
  • [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.

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

    主要问题是链表中间节点不易获得。

    思路1:链表转化成数组,然后上题做法。需要额外O(N)空间。时空复杂度O(N)

    思路2:每次都从头找到中间节点,时间复杂度为O(NlogN)。空间复杂度O(lgN),call stack的深度。 

    思路3:换一个思路,这次不top-down,而是bottom-up来做。一遍遍历链表,一遍中序遍历的顺序构建二叉树。时间复杂度O(N),空间复杂度O(lgN).

    public class Solution {
        public TreeNode sortedListToBST(ListNode head) {
            int len = 0;
            ListNode p = head;
            while (p != null) {
                len++;
                p = p.next;
            }
            ListNode[] wrap = new ListNode[1];
            wrap[0] = head;
            return SLtoBST(wrap, 0, len);
        }
    
        private TreeNode SLtoBST(ListNode[] wrap, int start, int end) {
            if (start >= end)
                return null;
            int mid = start + (end - start) / 2;
            TreeNode left = SLtoBST(wrap, start, mid);
            TreeNode root = new TreeNode(wrap[0].val);
            root.left = left;
            wrap[0] = wrap[0].next;
            root.right = SLtoBST(wrap, mid + 1, end);
            return root;
        }
    
        public static void main(String[] args) {
            ListNode head = ListUtils.makeList(1);
            TreeNode root = new Solution().sortedListToBST(head);
        }
    
    }
    View Code

    第二遍整理:注意类变量head的运用

    public class Solution {
        private ListNode head;
        public TreeNode sortedListToBST(ListNode head) {
            this.head=head;
            int len=0;
            ListNode cur=head;
            while(cur!=null){
                len++;
                cur=cur.next;
            }
            
            return toBST(0,len-1);
        }
        
        private TreeNode toBST(int from, int to){
            if(from>to)
                return null;
            int mid = from+(to-from)/2;
            TreeNode left = toBST(from,mid-1);
            TreeNode root = new TreeNode(head.val);
            root.left=left;
            head=head.next;
            root.right=toBST(mid+1,to);
            
            return root;
        }
    
    }

    第三遍记录:

      注意先统计list的长度,然后根据长度才能二分。

      中序遍历,先生成做子树,然后当前节点,然后生成右子树。

    参考:

    http://www.cnblogs.com/feiling/p/3267917.html

  • 相关阅读:
    球员岁月齐祖辉煌,执教生涯尤胜当年
    UVM序列篇之一:新手上路
    *2-3-7-加入field_automation机制
    2.3.6-加入scoreboard
    *2_3_5_加入reference model
    *2.3.4_封装成agent
    *2.3.3-加入monitor
    android的wake_lock介绍
    linux常用命令一些解释
    linux wc命令的作用。
  • 原文地址:https://www.cnblogs.com/jdflyfly/p/3821408.html
Copyright © 2011-2022 走看看