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.

    Solution: Recursion. Pre-order. O(n)

     1 /**
     2  * Definition for singly-linked list.
     3  * struct ListNode {
     4  *     int val;
     5  *     ListNode *next;
     6  *     ListNode(int x) : val(x), next(NULL) {}
     7  * };
     8  */
     9 /**
    10  * Definition for binary tree
    11  * struct TreeNode {
    12  *     int val;
    13  *     TreeNode *left;
    14  *     TreeNode *right;
    15  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
    16  * };
    17  */
    18 class Solution {
    19 public:
    20     TreeNode *sortedListToBST(ListNode *head) {
    21         return sortedListToBSTRe(head, getLength(head));
    22     }
    23     
    24     TreeNode* sortedListToBSTRe(ListNode* &head, int length)
    25     {
    26         if(length == 0) return NULL;
    27         int mid = length / 2;
    28         TreeNode* left = sortedListToBSTRe(head, mid);
    29         TreeNode* root = new TreeNode(head->val);
    30         TreeNode* right = sortedListToBSTRe(head->next, length - mid - 1);
    31         root->left = left;
    32         root->right = right;
    33         head = head->next;
    34         return root;
    35     }
    36     
    37     int getLength(ListNode* head) 
    38     {
    39         int length = 0;
    40         while(head) {
    41             length++;
    42             head = head->next;
    43         }
    44         return length;
    45     }
    46 };
  • 相关阅读:
    【Alpha】技术规格说明书
    【Alpha】第十次Scrum meeting
    【Alpha】第九次Scrum meeting
    【Alpha】第八次Scrum meeting
    【Alpha】第七次Scrum meeting
    【Alpha】特殊情况通知
    S2X环境搭建与示例运行
    [2018福大至诚软工助教]结对作业1测试结果
    机器学习
    机器学习
  • 原文地址:https://www.cnblogs.com/zhengjiankang/p/3646978.html
Copyright © 2011-2022 走看看