TreeNode *arrayToBST(vector<int> &A, int start, int end) {
     if (start > end)
         return NULL;
     int mid = start + (end - start) / 2;
     TreeNode *res = new TreeNode(A[mid]);
     if (start == end) {
         return res;
     } else {
         res->left = arrayToBST(A, start, mid - 1);
         res->right = arrayToBST(A, mid + 1, end);
         return res;
     }
 }
Ejemplo n.º 2
0
/* A helper function that copies contents of arr[] to Binary Tree.  
 This functon basically does Inorder traversal of Binary Tree and  
 one by one copy arr[] elements to Binary Tree nodes */
void arrayToBST (int *arr, struct node* root, int *index_ptr) 
{ 
  // Base Case 
  if (root == NULL) 
    return; 
  /* first update the left subtree */
  arrayToBST (arr, root->left, index_ptr); 
  /* Now update root's data and increment index */
  root->data = arr[*index_ptr]; 
  (*index_ptr)++; 
  /* finally update the right subtree */
  arrayToBST (arr, root->right, index_ptr); 
} 
// This function converts a given Binary Tree to BST
void binaryTreeToBST (struct node *root)
{
    // base case: tree is empty
    if(root == NULL)
       return;
 
    /* Count the number of nodes in Binary Tree so that
       we know the size of temporary array to be created */
    int n = countNodes (root);
 
    // Create a temp array arr[] and store inorder traversal of tree in arr[]
    int *arr = new int[n];
    int i = 0;
    storeInorder (root, arr, &i);
 
    // Sort the array using library function for quick sort
    qsort (arr, n, sizeof(arr[0]), compare);
 
    // Copy array elements back to Binary Tree
    i = 0;
    arrayToBST (arr, root, &i);
 
    // delete dynamically allocated memory to avoid meory leak
    delete [] arr;
}
    TreeNode *arrayToBST(const std::vector<int> &list_vec)
    {
		if (0 == list_vec.size())
		{
			return NULL;
		}
		if (1 == list_vec.size())
		{
			return new TreeNode(list_vec[0]);
		}
		TreeNode *now = new TreeNode(list_vec[list_vec.size() / 2]);
		std::vector<int> left(list_vec.begin(), list_vec.begin() + list_vec.size() / 2);
		std::vector<int> right(list_vec.begin() + list_vec.size() / 2 + 1, list_vec.end());
		now->left = arrayToBST(left);
		now->right = arrayToBST(right);
		return now;
	}
    TreeNode *sortedListToBST(ListNode *head) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
		if (NULL == head)
		{
			return NULL;
		}
		std::vector<int> list_vec;
		while (head)
		{
			list_vec.push_back(head->val);
			head = head->next;
		}
		return arrayToBST(list_vec);
    }
 /**
  * @param A: A sorted (increasing order) array
  * @return: A tree node
  */
 TreeNode *sortedArrayToBST(vector<int> &A) {
     // write your code here
     if (A.size() == 0)
         return NULL;
     return arrayToBST(A, 0, A.size() - 1);
 }