zoukankan      html  css  js  c++  java
  • [leetcode]Convert Sorted List to Binary Search Tree

    递归

    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
    /**
     * Definition for binary tree
     * 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 == nullptr) return nullptr;
            int len = 0;
            for(ListNode* curr = head ; curr ; curr = curr->next) len++;
            make_tree(head , len);
        }
    private:
        TreeNode* make_tree(ListNode* lis , int n) {
            if(n <= 0) return nullptr;
            int mid = n / 2;
            ListNode* curr = lis;
            for(int i = 0 ;i < mid ; ++i) curr = curr -> next;
            TreeNode* root = new TreeNode(curr->val);
            root->left = make_tree(lis , mid);
            root->right = make_tree(curr->next , n - mid - 1);
            return root;
        }
    };
  • 相关阅读:
    Max Sum Plus Plus HDU
    Monkey and Banana HDU
    Ignatius and the Princess IV HDU
    Extended Traffic LightOJ
    Tram POJ
    Common Subsequence HDU
    最大连续子序列 HDU
    Max Sum HDU
    畅通工程再续
    River Hopscotch POJ
  • 原文地址:https://www.cnblogs.com/x1957/p/3526144.html
Copyright © 2011-2022 走看看