leetcode

我的 leetcode 题解(JavaScript)


递归的把一个有序单向链表转化成二叉排序树

/**
 * 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* sortedListToBSTHelper(ListNode* head, ListNode* tail) {
        ListNode* slow = head;
        ListNode* fast = head;
        if(head==tail) return nullptr;

        while(fast!=tail && fast->next!=tail){
            fast = fast->next->next;
            slow = slow->next;
        }
        TreeNode* thead = new TreeNode(slow->val);
        thead->left = sortedListToBSTHelper(head,slow);
        thead->right = sortedListToBSTHelper(slow->next,tail);
        return thead;
    }
    TreeNode* sortedListToBST(ListNode* head) {
        if (head == nullptr) {
          return nullptr;
        } else {
          return sortedListToBSTHelper(head, nullptr);
        }
    }
};