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.

    解法:自底向上

         时间复杂度O(n), 空间复杂度O(logN)

     1 class Solution {
     2 public:
     3     TreeNode *sortedListToBST(ListNode *head) {
     4         if (head == NULL) return NULL;
     5         
     6         int len = 0;
     7         ListNode *p = head;
     8         while (p) {
     9             ++len;
    10             p = p->next;
    11         }
    12         
    13         return sortedListToBST(head, 0, len - 1);
    14     }
    15     
    16     TreeNode* sortedListToBST(ListNode *&head, int start, int end) {
    17         if (start > end) return NULL;
    18         
    19         int mid = start + (end - start) / 2;
    20         TreeNode *left_child = sortedListToBST(head, start, mid - 1);
    21         TreeNode *root = new TreeNode(head->val);
    22         root->left = left_child;
    23         head = head->next;
    24         root->right = sortedListToBST(head, mid + 1, end);
    25         
    26         return root;
    27     }
    28 };

     参考资料:

      1.http://leetcode.com/2010/11/convert-sorted-list-to-balanced-binary.html

  • 相关阅读:
    Configuration Management
    Android Hooking
    技术趋势总结
    Maven Repo Mirror
    拥抱JAVA
    NPM 更新所有依赖项
    Knockout Mvc Compoment FrameSet With Typescript
    Knockoutjs Component问题汇总
    前端编码规范文档
    优秀程序设计的18大原则
  • 原文地址:https://www.cnblogs.com/vincently/p/4301973.html
Copyright © 2011-2022 走看看