zoukankan      html  css  js  c++  java
  • LeetCode题解之Convert Sorted List to Binary Search Tree

    1、题目描述

    2、题目描述

    使用快慢指针寻找链表中间值。

    3、代码

     1 TreeNode* sortedListToBST(ListNode* head) {
     2         if (head == NULL)
     3             return NULL;
     4         
     5         ListNode *mid = findmid(head);
     6         
     7         TreeNode *node = new TreeNode(mid->val);
     8         
     9         if (head == mid)
    10             return node;
    11         
    12         node->left = sortedListToBST(head);
    13         node->right = sortedListToBST(mid->next);
    14         return node;
    15         
    16     }
    17     
    18    
    19     
    20     ListNode *findmid(ListNode* left)
    21     {
    22         ListNode *preptr = NULL;
    23         ListNode *slow = left;
    24         ListNode *fast = left;
    25         
    26         while (fast != NULL && fast->next != NULL) {
    27             preptr = slow;
    28             slow = slow->next;
    29             fast = fast->next;
    30             fast = fast->next;
    31         }
    32         if (preptr != NULL)
    33             preptr->next = NULL;    
    34         return slow;
    35     }
    36     
  • 相关阅读:
    Seaborn相关
    Matplot相关(二)——统计图
    PAT 甲级真题
    数学题一
    Codeforces Round #467 (Div. 2)
    国庆 Day1
    [NOIP 2005] 运输计划
    dp专题练习
    YBT 2.4 AC自动机
    [模板]树链剖分
  • 原文地址:https://www.cnblogs.com/wangxiaoyong/p/10434145.html
Copyright © 2011-2022 走看看