zoukankan      html  css  js  c++  java
  • 109. 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.
    从给定的有序链表生成平衡二叉树。
    解题思路:最容易想到的就是利用数组生成二叉树的方法,找到中间节点作为二叉树的root节点,然后分别对左右链表递归调用分别生成左子树和右子树。时间复杂度O(N*lgN)

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

     空间为O(1)时间为O(n):

    TreeNode *sortedListToBST(ListNode *head)  
    {  
        int len = 0;  
           ListNode * node = head;  
           while (node != NULL)  
           {  
               node = node->next;  
               len++;  
           }  
           return buildTree(head, 0, len-1);  
       }  
         
       TreeNode *buildTree(ListNode *&node, int start, int end)  
       {  
           if (start > end) return NULL;  
           int mid = start + (end - start)/2;  
           TreeNode *left = buildTree(node, start, mid-1);  
           TreeNode *root = new TreeNode(node->val);  
           root->left = left;  
           node = node->next;  
           root->right = buildTree(node, mid+1, end);  
           return root;  
       }  

    参考:

    http://blog.csdn.net/salutlu/article/details/24502109

    http://blog.csdn.net/worldwindjp/article/details/39722643

    https://www.nowcoder.com/questionTerminal/86343165c18a4069ab0ab30c32b1afd0

  • 相关阅读:
    Python基础之面向对象3(继承)
    Python基础之面向对象2(封装)
    python基础之面向对象1
    Python基础之变量作用域
    Python基础之函数参数
    Python基础之函数
    Python基础 之for循环嵌套实例
    Python基础之集合
    Python基础之元组和字典
    Python基础之列表深浅复制和列表推导式
  • 原文地址:https://www.cnblogs.com/zle1992/p/7696082.html
Copyright © 2011-2022 走看看