1. 程式人生 > >Crack LeetCode 之 109. Convert Sorted List to Binary Search Tree

Crack LeetCode 之 109. Convert Sorted List to Binary Search Tree

http://oj.leetcode.com/problems/convert-sorted-list-to-binary-search-tree/

對一個BST做中序遍歷,就得到了一個有序連結串列;同理,如果按照中序遍歷的順序對有序連結串列中的節點建立BST,便得到了對應的BST。以下程式碼用遞迴的方法以中序遍歷的順序建立BST。

C++程式碼如下,時間複雜度是O(n),空間複雜度是O(logn)。

class Solution {
public:
    TreeNode* sortedListToBST(ListNode* head)
	{
		if ( head == NULL )
			return NULL;

		vector<ListNode*> elements;
		elements.push_back(head);

		int count = 0;
		while ( head ) {
			count++;
			head = head->next;
		}

		return helper( elements, 0, count-1 );
    }

	TreeNode* helper(vector<ListNode*> & elements, int l, int r)
	{
		if (l > r)
			return NULL;
		
		int m = (l+r)/2;
		TreeNode* left = helper(elements, l, m-1);
		TreeNode* root = new TreeNode( elements[0]->val );
		elements[0] = elements[0]->next;
		root->left = left;
		root->right = helper(elements, m+1, r);

		return root;
	}
};