lintcode 106. sorted linked list into a binary search tree

All the elements are given in a single list in ascending order, to convert it into a highly balanced binary search tree

样例
样例 1:
	输入: array = 1->2->3
	输出:
		 2  
		/ \
		1  3
		
样例 2:
	输入: 2->3->6->7
	输出:
		 3
		/ \
	   2   6
		     \
		      7

	解释:
	可能会有多个符合要求的结果,返回任意一个即可。
/**
 * Definition of ListNode
 * class ListNode {
 * public:
 *     int val;
 *     ListNode *next;
 *     ListNode(int val) {
 *         this->val = val;
 *         this->next = NULL;
 *     }
 * }
 * Definition of TreeNode:
 * class TreeNode {
 * public:
 *     int val;
 *     TreeNode *left, *right;
 *     TreeNode(int val) {
 *         this->val = val;
 *         this->left = this->right = NULL;
 *     }
 * }
 */


class Solution {
public:
    /*
     * @param head: The first node of linked list.
     * @return: a tree node
     */
    TreeNode * sortedListToBST(ListNode * head) {
        // write your code here
        vector<int> tmp;
        while(head)
        {
            tmp.push_back(head->val);
            head=head->next;
        }
        if(tmp.empty()) return NULL;
        TreeNode*newroot=builtree(tmp,0,tmp.size()-1);
        return newroot;
    }
    TreeNode*builtree(vector<int>&A,int low,int high)
    {
        if(low>high) return NULL;
        int mid=low+(high-low)/2;
        TreeNode* newroot=new TreeNode(A[mid]);
        newroot->left=builtree(A,low,mid-1);
        newroot->right=builtree(A,mid+1,high);
        return newroot;
    }
};
Published 369 original articles · won praise 15 · views 10000 +

Guess you like

Origin blog.csdn.net/weixin_43981315/article/details/104010053