zoukankan      html  css  js  c++  java
  • 【LeetCode】109&

    Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.

    Solution 1:  recursion 

    runtime: 28ms.

    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
    /**
     * Definition for a binary tree node.
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution {
    public:
        TreeNode* sortedListToBST(ListNode* head) {
            if(!head)return NULL;
            ListNode *temp=head;
            int length=0;
            while(temp){
                length++;
                temp=temp->next;
            }
            return sortedListToBST(head, 0, length-1);
        }
        TreeNode* sortedListToBST(ListNode *& head, int begin, int end){
            if(begin>end)return NULL;
            int mid=begin+(end-begin)/2;
            TreeNode *left=sortedListToBST(head,begin,mid-1);
            TreeNode *root=new TreeNode(head->val);
            head=head->next;
            TreeNode *right=sortedListToBST(head,mid+1,end);
            root->left=left;
            root->right=right;
            return root;
        }

    TreeNode* sortedArrayToBST(vector<int>& nums) {

    int n=nums.size();
    return sortedArrayToBST(nums, 0, n-1);

    }

    TreeNode* sortedArrayToBST(vector<int>& nums, int start,int end) {

    if (start > end) return NULL;
    int mid = start + (end - start) / 2;

    TreeNode *node = new TreeNode(nums[mid]);
    node->left = sortedArrayToBST(nums, start, mid-1);
    node->right = sortedArrayToBST(nums, mid+1, end);
    return node;

    }

    };

    Solution 2:https://leetcode.com/discuss/29826/clean-c-solution-recursion-o-nlogn-with-comment

  • 相关阅读:
    Linux ps 查看进程
    Linux free命令
    Linux sar命令
    php 上传文件
    sql 计算周围公里语句
    mysql sum 和 count 函数 合并使用
    php函数 ceil floor round和 intval
    linux sort 命令
    Sicily 2711. 模板与STL 解题报告
    堆排序
  • 原文地址:https://www.cnblogs.com/irun/p/4759046.html
Copyright © 2011-2022 走看看