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

    跟上一题一样,只是数据结构换成了链表,这里求链表的中位数还是乖乖用len先计算长度吧,用slow、fast指针还得先标记尾指针,反而更麻烦。

     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     void buildTree(TreeNode *&root, ListNode *head, int len) {
    21         if (len <= 0) return;
    22         ListNode *mid = head;
    23         for (int i = 0; i < len / 2; ++i) {
    24             mid = mid->next;
    25         }
    26         root = new TreeNode(mid->val);
    27         ListNode *head2 = mid->next;
    28         mid = NULL;
    29         buildTree(root->left, head, len / 2);
    30         buildTree(root->right, head2, (len - 1) / 2);
    31     }
    32     
    33     TreeNode *sortedListToBST(ListNode *head) {
    34         int len = 0;
    35         for (ListNode *p = head; p!= NULL; p = p->next) {
    36             ++len;
    37         }
    38         TreeNode *root = NULL;
    39         buildTree(root, head, len);
    40         return root;
    41     }
    42 };
  • 相关阅读:
    绍一集训Round#2
    CF 799B T-shirt buying
    Luogu P2827 蚯蚓
    Luogu P4053 [JSOI2007]建筑抢修
    【LGR-049】洛谷7月月赛
    浅谈可持久化数据结构
    CF 888E Maximum Subsequence
    在平衡树的海洋中畅游(三)——Splay
    浅谈单调栈/队列
    CF 859E Desk Disorder
  • 原文地址:https://www.cnblogs.com/easonliu/p/3644316.html
Copyright © 2011-2022 走看看