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

Leetcode Convert Sorted List to Binary Search Tree

时间:2014-06-26 00:12:57      阅读:289      评论:0      收藏:0      [点我收藏+]

标签:style   class   blog   code   ext   color   

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

TreeNode *createSearchTree(ListNode *&head, int left , int right){
    if(left > right) return NULL;
    int mid = (left + right)>>1;
    TreeNode *leftChild = createSearchTree(head,left,mid-1);
    TreeNode *parent = new TreeNode(head->val);
    parent->left = leftChild;
    head = head->next;
    parent->right = createSearchTree(head,mid+1,right);
    return parent;
}

TreeNode *sortedListToBST(ListNode *head) {
    if(head == NULL) return NULL;
    int len = 0;
    ListNode *p = head;
    while(p){len++; p = p->next;}
    return createSearchTree(head,0,len-1);    
}

 

Leetcode Convert Sorted List to Binary Search Tree,布布扣,bubuko.com

Leetcode Convert Sorted List to Binary Search Tree

标签:style   class   blog   code   ext   color   

原文地址:http://www.cnblogs.com/xiongqiangcs/p/3804196.html

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