Interview Question
Country: United States
I suppose that if you are just creating an arbitrary tree that is height balanced by and input you could recursively create the tree and stop when you hit a height equal to the provided level.
static BSTNode create_i(int height, int count)
{
if (height == count)
return null;
BSTNode n = new BSTNode();
n.Data = count++;
n.Left = create_i(height, count);
n.Right = create_i(height, count);
return n;
}
Assuming the binary tree does not need to be a BST, simplest approach is to flatten out the tree first into an array, using depth-first search. The array will tell you how many elements exist, and which should be the root of a subtree; advantage of an array, is that you can pivot on any element(this is how quicksort does balancing internally!). The level input into the function merely tells you when to stop processing.
- Yev August 05, 2012