码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode: Convert Sorted Array to Binary Search Tree && Convert Sorted List to Binary Search Tree

时间:2015-05-13 18:28:36      阅读:126      评论:0      收藏:0      [点我收藏+]

标签:

Title:

Given an array where elements are sorted in ascending order, convert it to a height balanced BST.

 

Title:

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 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) {
        return maker(head,getLength(head));
    }
    TreeNode* maker(ListNode* head, int len){
        if (len == 0)
            return NULL;
        if (len == 1)
            return new TreeNode(head->val);
        ListNode* cur = getN(head,len/2);
        TreeNode* root = new TreeNode(cur->val);
        root->left = maker(head,len/2);
        root->right = maker(cur->next,len-len/2-1);
    }
    ListNode* getN(ListNode*p, int n){
        ListNode* l = p;
        int count = 0;
        while (count++ < n){
            l = l->next;
        }
        return l;
    }
    
    int getLength(ListNode* p){
        ListNode * l = p;
        int len = 0;
        while (l){
            len++;
            l = l->next;
        }
        return len;
    }
};

 

自底向上

class Solution {
public:
TreeNode *sortedListToBST(ListNode *head) {
    int len = 0;
    ListNode *p = head;
    while (p) {
        len++;
        p = p->next;
    }
    return sortedListToBST(head, 0, len - 1);
}
private:
    TreeNode* sortedListToBST(ListNode*& list, int start, int end) {
    if (start > end) return nullptr;
    int mid = start + (end - start) / 2;
    TreeNode *leftChild = sortedListToBST(list, start, mid - 1);
    TreeNode *parent = new TreeNode(list->val);
    parent->left = leftChild;
    list = list->next;
    parent->right = sortedListToBST(list, mid + 1, end);
    return parent;
    }
};

 

LeetCode: Convert Sorted Array to Binary Search Tree && Convert Sorted List to Binary Search Tree

标签:

原文地址:http://www.cnblogs.com/yxzfscg/p/4500855.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!