leetcode-----109. 有序链表转换二叉搜索树

代码

/**
 * 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) {
        if (!head) return NULL; 
        int n  = 0;
        for (auto p = head; p; p = p->next) n++;
        if (n == 1) return new TreeNode(head->val);

        auto cur = head;
        for (int i = 0; i < n / 2 - 1; ++i) cur = cur->next;
        auto root = new TreeNode(cur->next->val);
        root->right = sortedListToBST(cur->next->next);
        cur->next = NULL;
        root->left = sortedListToBST(head);
        return root;
    }
};

猜你喜欢

转载自www.cnblogs.com/clown9804/p/13376061.html