• LeetCode: Convert Sorted Array to Binary Search Tree && Convert Sorted List to Binary Search Tree


    Title:

    Given an array where elements are sorted in ascending order, convert it to a height balanced BST.

    Title:

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

    思路:自顶向下

    /**
     * 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) {
            return maker(head,getLength(head));
        }
        TreeNode* maker(ListNode* head, int len){
            if (len == 0)
                return NULL;
            if (len == 1)
                return new TreeNode(head->val);
            ListNode* cur = getN(head,len/2);
            TreeNode* root = new TreeNode(cur->val);
            root->left = maker(head,len/2);
            root->right = maker(cur->next,len-len/2-1);
        }
        ListNode* getN(ListNode*p, int n){
            ListNode* l = p;
            int count = 0;
            while (count++ < n){
                l = l->next;
            }
            return l;
        }
        
        int getLength(ListNode* p){
            ListNode * l = p;
            int len = 0;
            while (l){
                len++;
                l = l->next;
            }
            return len;
        }
    };

    自底向上

    class Solution {
    public:
    TreeNode *sortedListToBST(ListNode *head) {
        int len = 0;
        ListNode *p = head;
        while (p) {
            len++;
            p = p->next;
        }
        return sortedListToBST(head, 0, len - 1);
    }
    private:
        TreeNode* sortedListToBST(ListNode*& list, int start, int end) {
        if (start > end) return nullptr;
        int mid = start + (end - start) / 2;
        TreeNode *leftChild = sortedListToBST(list, start, mid - 1);
        TreeNode *parent = new TreeNode(list->val);
        parent->left = leftChild;
        list = list->next;
        parent->right = sortedListToBST(list, mid + 1, end);
        return parent;
        }
    };
  • 相关阅读:
    python之九九乘法表
    python选择排序有序区域和无序区域
    mysql学习笔记(一)
    cuda toolkit安装
    vs 无法打开输入文件“kernel32.lib”
    vs libtorch 无法定位程序输入点…于动态链接库…exe
    libtorch 部署 windows10
    openvino记录
    AcWing 803.区间合并
    AcWing 802.区间和
  • 原文地址:https://www.cnblogs.com/yxzfscg/p/4500855.html
Copyright © 2020-2023  润新知