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     }
  • 相关阅读:
    线程练习-网络买票
    永久储存信息(已完善)
    Linux命令
    oracle(3)
    小结
    java开发中中文编码问题
    double保留两位小数
    oracle(2)
    javadate相关
    分布式
  • 原文地址:https://www.cnblogs.com/guyufei/p/3448834.html
Copyright © 2011-2022 走看看