solution.cpp 934 字节
Newer Older
每日一练社区's avatar
每日一练社区 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
#include <cstddef>

struct ListNode
{
    int val;
    ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};

struct TreeNode
{
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};

class Solution
{
public:
    TreeNode *sortedListToBST(ListNode *head)
    {
        auto n = [](ListNode *p)
        {
            int count{0};
            for (; p; p = p->next, ++count)
                ;
            return count;
        }(head);
        return sortedListToBST(&head, n);
    }
    TreeNode *sortedListToBST(ListNode **head_ref, int n)
    {
        if (n < 1)
            return NULL;
        TreeNode *left = sortedListToBST(head_ref, n / 2);
        TreeNode *root = new TreeNode((*head_ref)->val);
        root->left = left;
        *head_ref = (*head_ref)->next;
        root->right = sortedListToBST(head_ref, n - n / 2 - 1);
        return root;
    }
};