1957

无聊蛋疼的1957写的低端博客
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

[leetcode]Convert Sorted List to Binary Search Tree

Posted on 2014-01-19 19:52  1957  阅读(135)  评论(0编辑  收藏  举报

递归

 

/**
 * 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;
    }
};