`
cozilla
  • 浏览: 89215 次
  • 性别: Icon_minigender_1
  • 来自: 南京
社区版块
存档分类
最新评论

[Leetcode] Convert Sorted List to Binary Search Tree

阅读更多
Convert Sorted List to Binary Search TreeOct 3 '125768 / 16298

Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.

 

 

/**
 * 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 == NULL) return NULL;
        ListNode* t = head;
        int len = 0;
        while (t != NULL) len++, t = t->next;
        return gen(head, 0, len - 1);
    }
    
    TreeNode *gen(ListNode* &cur, int start, int end) {
        if (start > end) return NULL;
        int mid = start + (end -start) / 2;
        TreeNode *left = gen(cur, start, mid - 1);
        TreeNode *node = new TreeNode(cur->val);
        cur = cur->next;
        node->left = left;
        node->right = gen(cur, mid+1, end);
    }
};

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics