当前位置: 代码迷 >> 综合 >> lintcode 106. 排序列表转换为二分查找树
  详细解决方案

lintcode 106. 排序列表转换为二分查找树

热度:98   发布时间:2023-11-21 02:41:19.0

题目:给出一个所有元素以升序排序的单链表,将它转换成一棵高度平衡的二分查找树

思路:每次取一个中间元素,递归。

class Solution {

public:
    /*
     * @param head: The first node of linked list.
     * @return: a tree node
     */
    TreeNode * func(int left,int right,vector<int> arr){
        if(right<left) return NULL;//? <=
        int mid=(left+right)/2;
        TreeNode *tree = new TreeNode(arr[mid]);
        tree->left=func(left,mid-1,arr);
        tree->right=func(mid+1,right,arr);
        return tree;
    }
    TreeNode * sortedListToBST(ListNode * head) {
        if(head==NULL) return NULL;
        vector<int> arr;
        ListNode *p=head;
        while(p!=NULL){
            arr.push_back(p->val);
            p=p->next;
        }
        return func(0,arr.size()-1,arr);
        
        // write your code here
    }

};

ps:树那里都要忘得差不多了 每天一道lintcode 捡起来