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

    Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.

    Solution:

     1     TreeNode *sortedListToBST(ListNode *head) {
     2         if(head == NULL)
     3             return NULL;
     4         if(head->next == NULL)
     5             return new TreeNode(head->val);
     6             
     7         ListNode * current = head;
     8         int size = 0;
     9         while(current != NULL){
    10             size ++;
    11             current = current->next;
    12         }
    13         current = head;
    14         int median = size / 2;
    15         int count = 0;
    16         ListNode * median_node = NULL;
    17         ListNode * pre_node = NULL;
    18         while(current != NULL){
    19             if(count == median){
    20                 median_node = current;
    21                 pre_node->next = NULL;
    22                 break;
    23             }
    24             count ++;
    25             pre_node = current;
    26             current = current->next;
    27         }
    28         TreeNode * root = new TreeNode(median_node->val);
    29         root->left = sortedListToBST(head);
    30         root->right = sortedListToBST(median_node->next);
    31         return root;
    32     }
  • 相关阅读:
    KMP算法精髓
    习题
    JavaScript function函数种类介绍
    街景地图 API
    电脑网卡
    框架的设计之IRepository还是IRepository<T>
    顺序线性表
    hdu4284之字典树
    pt-table-checksum
    C++中输入输出流及文件流操作笔记
  • 原文地址:https://www.cnblogs.com/guyufei/p/3448834.html
Copyright © 2011-2022 走看看