zoukankan      html  css  js  c++  java
  • 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;
        }
    };
  • 相关阅读:
    Cocos2dx隐藏iOS7状态栏】通过添加Plist Key隐藏iOS7状态栏
    数论
    Large Division(大数取余模板)
    CodeForces
    2019山东第十届acm省赛 c Wandering Robot 即zoj4115
    CF1157A. Reachable Numbers
    E. Mishap in Club (CF 245E)
    ATcoder Big Array
    CF987B
    CF1013B And
  • 原文地址:https://www.cnblogs.com/yxzfscg/p/4500855.html
Copyright © 2011-2022 走看看