【发布时间】:2016-11-16 06:24:28
【问题描述】:
我已经尝试解决这个问题两天了,但我不知道如何将数组表示为堆(从左到右)。我尝试在其他网站上寻找答案,但找不到。
问题是有一个给定的数组。比如……
{26,5,3,2,1,1...}
我需要将它转换成这样的无序堆。
26
/ \
5 3
/ \
2 1
到目前为止,我所做的是这样,但我无法弄清楚如何检查最左边的子节点是否先填充,然后再转到右边的节点。
package myTest;
public class UnsortedBT {
static int[] unsortedArr = new int[]{26,5,3,2,1,1,10,2,4};
public static void main(String[] args) {
// TODO Auto-generated method stub
UnsortedBT c = new UnsortedBT();
BinaryTree tree = c.new BinaryTree(unsortedArr[0]);
for(int i=1 ;i<unsortedArr.length;i++)
{
BinaryTree newTree = c.new BinaryTree(unsortedArr[i]);
tree.insert(newTree);
}
System.out.println(tree.left.left.right.data);
}
public class BinaryTree{
private BinaryTree right;
private BinaryTree left;
private int data;
public BinaryTree(int s){
data = s;
right = null;
left = null;
}
public int checkTree(){
if(left == null && right == null){
return 1;
}else if(left == null){
return 1 + right.checkTree();
}else if(right == null){
return 1 + left.checkTree();
}else{
return 1 + left.checkTree() + right.checkTree();
}
}
public void insert(BinaryTree bt){
if(left == null){
setLeft(bt);
}else if(right == null){
setRight(bt);
}else{
int leftCheck = left.checkTree();
int rightCheck = right.checkTree();
// The problem is lies here
if(leftCheck==rightCheck||left!=null&&left==null){
left.insert(bt);
}else{
right.insert(bt);
}
}
}
public void setLeft (BinaryTree l){ left = l; }
public void setRight(BinaryTree r){ right = r; }
}
}
【问题讨论】:
-
这篇博客文章和后面的文章应该可以帮助你:blog.mischel.com/2013/09/29/a-better-way-to-do-it-the-heap
-
这是排序堆先生。我正在做未排序的。
-
没有“无序堆”这样的东西。堆具有特定的结构,实际上是有序的。看起来您正在尝试从任意数组创建平衡的左填充二叉树。碰巧您选择的数组表示创建了一个最大堆树。
标签: arrays algorithm heap binary-tree