您的位置:首页 > 其它

Test

2012-02-24 05:29 134 查看
/**
* Will receive a heap integer array and return the height of the subtree rooted
* at the 3rd smallest value
*
* @param heap
*            0-based integer array
* @return Height of the subtree rooted at the 3rd smallest value
*/
public int subTreeHeight(int[] heap) {
// TODO You must implement this method
if(!isHeap(heap))	// Test if the tested Heap is a valid Heap
return -1;
else if(heap.length < 3 || heap[1] == -1 || heap[2] == -1) // while the elements in Heap less than 3, there is no third smallest element
return -1;
else if(heap[1] <= heap[2]) {
if(heap[3] != -1 && heap[3] < heap[2])
return getSubHeight(heap, 3);
else if(heap[4] != -1 && (heap[4] < heap[3] && heap[4] < heap[2]))
return getSubHeight(heap, 4);
else if(heap[4] != -1 && (heap[3] <= heap[4] && heap[3] < heap[2]))
return getSubHeight(heap, 3);
else
return getSubHeight(heap, 2);
} else {
if(heap[5] != -1 && heap[5] < heap[1])
return getSubHeight(heap, 5);
else if(heap[6] != -1 && (heap[6] < heap[5] && heap[6] < heap[1]))
return getSubHeight(heap, 6);
else if(heap[6] != -1 && (heap[5] <= heap[6] && heap[5] < heap[1]))
return getSubHeight(heap, 5);
else
return getSubHeight(heap, 1);
}
}

/**
* @description get the height of subtree which rooted heap

* @param int[] heap
* @param int n
* @return height of subtree
*/
private int getSubHeight(int[] heap, int n) {
int heigth = 0;
while((NUM * n + 1) < heap.length)
{
if(heap[NUM*n +1] != -1)
heigth++;
n = NUM * n + 1;
}
return heigth;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: