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

    思路:才用快慢指针,找到中间节点,然后递归处理。

    accepted code:

     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         if(head==nullptr)
    22         return nullptr;
    23         return toBST(head,nullptr);
    24     }
    25     
    26     TreeNode* toBST(ListNode* head,ListNode* end)
    27     {
    28         ListNode* slow=head;
    29         ListNode* fast=head;
    30         if(head==end)
    31         return nullptr;
    32         
    33         while(fast!=end&&fast->next!=end)
    34         {
    35             fast=fast->next->next;
    36             slow=slow->next;
    37         }
    38         
    39         TreeNode* root=new TreeNode(slow->val);
    40         root->left=toBST(head,slow);
    41         root->right=toBST(slow->next,end);
    42         return root;
    43     }
    44 };
  • 相关阅读:
    CodeForces
    CodeForces
    CodeForces
    HDU 6704 K-th occurrence(后缀数组,主席树,st表,二分)
    AcWing 1004. 品酒大会 (后缀数组,并查集)
    Gym
    codeforces 2100左右的DS题 做题记录
    P4768 [NOI2018] 归程 做题记录
    CSP 2021 智熄记
    「随笔」论打羽毛球的正确姿势
  • 原文地址:https://www.cnblogs.com/hongyang/p/6419203.html
Copyright © 2011-2022 走看看