[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;
    }
};

 

你可能感兴趣的:(Binary search)