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

    思路:
    递归

    代码:

     1     TreeNode *sortedListToBST(ListNode *head, int len){
     2         if(len == 0){
     3             return NULL;
     4         }
     5         TreeNode *result = new TreeNode(0);
     6         if(len == 1){
     7             result->val = head->val;
     8             return result;
     9         }
    10         ListNode *listNode = head;
    11         for(int i = 0; i < len/2; i++)
    12             listNode = listNode->next;
    13         result->val = listNode->val;
    14         result->left = sortedListToBST(head, len/2);
    15         result->right = sortedListToBST(listNode->next, (len-1)/2);
    16         return result;
    17     }
    18     TreeNode *sortedListToBST(ListNode *head) {
    19         // IMPORTANT: Please reset any member data you declared, as
    20         // the same Solution instance will be reused for each test case.
    21         if(head == NULL)
    22             return NULL;
    23         ListNode *listNode = head;
    24         int len = 0;
    25         while(listNode){
    26             len++;
    27             listNode = listNode->next;
    28         }
    29         return sortedListToBST(head, len);
    30     }
  • 相关阅读:
    go-go协程
    linux-pclint代码检测
    linux-32位-交叉编译openssl
    go-json类
    mysql-定时任务
    go-IO操作
    go-异常处理-error-panic-recover
    go-defer语句
    go-select
    go-指针
  • 原文地址:https://www.cnblogs.com/waruzhi/p/3414863.html
Copyright © 2011-2022 走看看