• [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.

    解题思路:

     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 a binary tree node.
    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 sortedListToBST(head, len(head));
    22     }
    23 private:
    24     TreeNode *sortedListToBST(ListNode *head, int len) {
    25         if (len == 0) return nullptr;
    26         if (len == 1) return new TreeNode(head->val);
    27         
    28         int mid = len / 2;
    29         TreeNode *root = new TreeNode((afterNthNode(head, mid))->val);
    30         root->left = sortedListToBST(head, mid);
    31         root->right = sortedListToBST(afterNthNode(head, mid + 1), len - mid - 1);
    32         
    33         return root;
    34     }
    35     
    36     int len(ListNode *head) {
    37         int n = 0;
    38         while (head) {
    39             head = head->next;
    40             ++n;
    41         }
    42         
    43         return n;
    44     }
    45     
    46     ListNode *afterNthNode(ListNode *head, int n) {
    47         while (n--) {
    48             head = head->next;
    49         }
    50         
    51         return head;
    52     }
    53 };
  • 相关阅读:
    LightOJ 1094
    hdu 2586
    hdu 5234
    hdu 2955
    LightOJ 1030 数学期望
    poj 1273
    CodeIgniter学习笔记(十五)——CI中的Session
    CodeIgniter学习笔记(十四)——CI中的文件上传
    CodeIgniter学习笔记(十三)——CI中的分页
    CodeIgniter学习笔记(十二)——CI中的路由
  • 原文地址:https://www.cnblogs.com/skycore/p/5055392.html
Copyright © 2020-2023  润新知