Is there a way to turn a Binary to a sorted array without having to traverse the tree for every array index?
Node root;
Node runner;
int current_smallest;
void findsmallest(Node root){
//Pre-order traversal
if(root == null){
return;
}else{
runner = root;
if(current_smallest == null){
current_smallest = runner.element;
}else{
if(current_smallest > runner.element){
current_smallest = runner.element;
}
}
findsmallest(runner.left);
findsmallest(runner.right);
}
}
void fill_array( int [] array ){
for(int i =0; i < array.length(); i++){
findsmallest(root);
array[i] = current_smallest;
}
}
As you can see this can be take a long time if there are a lot of nodes in the tree. Btw, I forgot to show that the whole tree would have to be traversed at the start to get the length of the array.
Yes, you can do that: run an in-order traversal of the tree, keep the current position of the array, and store the node's value at the then-current position of the array.
You can do in-order traversal recursively, or you can do it with a stack data structure. If you want to do it recursively, you can do this:
int fill_array(Node root, int [] array, int pos) {
if (root.left != null) {
pos = fill_array(root.left, array, pos);
}
array[pos++] = root.element;
if (root.right != null) {
pos = fill_array(root.right, array, pos);
}
return pos; // return the last position filled in by this invocation
}
Note that in order for the above recursive procedure to work, the caller must allocate enough space in the array
passed into the function.
A binary tree can be represented in an array; if this were the case, all you would need to do is sort the array.
Here's some more info on representing the tree in the array: wikipedia
This is not necessarily the most space-efficient representation; the "nodes with references" representation may waste less space.
What you want is an in-order traversal, which is generally implemented recursively like:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With