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 };
  • 相关阅读:
    day03接口的初期认识
    day03模板方法设计模式
    day02抽象类的练习
    day02抽象类1
    final 关键字
    day01子类与父类特点
    day01继承extends
    day01函数的重载
    图解HTTPS
    编译的时候遇到 The type java.lang.Object cannot be resolved.
  • 原文地址:https://www.cnblogs.com/hongyang/p/6419203.html
Copyright © 2011-2022 走看看