Converting Binary Tree into a sorted array
Following my previous question, I would like now to put the Binary Tree values in a sorted array.
So, first I used my numOfNodeswn function that counts total sum of nodes in my tree,
I created an array according to the开发者_如何学编程 result of this function and I started to think that Instead of locating the minimum value of the tree and making not-that-easy successor function, I can simply take advantge of the utility of this kind of tree and make a kind of Inorder process, which during it I can put the correct values into my array.
My main problem is to control of variable i- which is the index according to it, I will know exactly where to put the correct values.
(header is the the head of the tree)
This is what I wrote so far:
public double[] toDoubleArray() {
double[] arr = new double[numOfNodeswn(header)];
int i=0;
return putvalues(arr, i, header);
}
private double[] putvalues(double[] arr, int i, RBNode t) {
if (t!=null){
putvalues (arr, i, t.left);
arr[i]=t.value;
i++;
putvalues (arr, i, t.right);
}
return arr;
}
I think you need to do a depth first iteration over the binary tree. Load each entry into th tree and increment the index as you go. The result should be a sorted array.
You're correct to do an in-order traversal of the tree. Perhaps instead of returning arr
you should return an integer, corresponding to the first open spot in the array. This seems like a homework assignment, so I don't want to give too much away.
精彩评论