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;
        }
    };
  • 相关阅读:
    Android_学习系列(33)--App应用之提交到各大市场渠道
    Android_TextView使用Spanable
    6 种CSS设置居中的方法
    如何设置Grunt
    C#中的Collection 3
    C#中的Collection 2
    C#中的Collection 1
    网页上的JS call Unity3d里的function——SendMessage
    关于WebPlayer Sandbox的小节
    完整Deploy WebPlayer的Config
  • 原文地址:https://www.cnblogs.com/yxzfscg/p/4500855.html
Copyright © 2011-2022 走看看