Interview Question

Software Engineer Intern Interview(Student Candidate)

- Convert sorted array to BST - Print the above tree level

  by level - I forgot the last question
Answer

Interview Answer

1 Answer

1

BinaryTree* sortedArrayToBST(int arr[], int start, int end) {
  if (start > end) return NULL;
  // same as (start+end)/2, avoids overflow.
  int mid = start + (end - start) / 2;
  BinaryTree *node = new BinaryTree(arr[mid]);
  node->left = sortedArrayToBST(arr, start, mid-1);
  node->right = sortedArrayToBST(arr, mid+1, end);
  return node;
}

BinaryTree* sortedArrayToBST(int arr[], int n) {
  return sortedArrayToBST(arr, 0, n-1);
}

thy on Nov 17, 2013

Add Answers or Comments

To comment on this question, Sign In with Facebook or Sign Up