实现步骤
1、创建二叉树结点类
2、根据数组的数字创建二叉树结点对象的集合
3、补充完整各个二叉树结点的左右子树
4、对集合从尾部至头部依次遍历,将该结点与左右子树进行比较和交换。
代码实现
public class BigTopHeap {
public static void main(String[] args) {
//int[] ints = {9, 3, 6, 7, 5, 8, 1, 0, 4, 2};
int[] ints = {2, 8, 7, 1, 3, 5, 6, 4};
List<Node> list = new ArrayList<>();
for (int anInt : ints) {
list.add(new Node(anInt));
}
for (int i = 0; i < list.size(); i++) {
int left = i * 2 + 1;
int right = i * 2 + 2;
if (left < list.size()) {
list.get(i).setLeft(list.get(left));
}
if (right < list.size()) {
list.get(i).setRight(list.get(right));
} else {
break;
}
}
System.out.println(list.size());
for (int i = list.size() - 1; i >= 0; i--) {
Node node = list.get(i);
check(node);
}
for (Node node : list) {
System.out.print(node.getVal() + ",");
}
}
private static void check(Node root) {
Node left = root.getLeft();
Node right = root.getRight();
if (left != null && right != null) {
Node node = left.getVal() > right.getVal() ? left : right;
if (node.getVal() > root.getVal()) {
int val = root.getVal();
root.setVal(node.getVal());
node.setVal(val);
check(node);
}
} else if (left != null) {
if (left.getVal() > root.getVal()) {
int val = root.getVal();
root.setVal(left.getVal());
left.setVal(val);
check(left);
}
} else if (right != null) {
if (right.getVal() > root.getVal()) {
int val = root.getVal();
root.setVal(right.getVal());
right.setVal(val);
check(right);
}
}
}
private static class Node {
private int val;
private Node left;
private Node right;
public Node(int val) {
this.val = val;
}
public Node(int val, Node left, Node right) {
this.val = val;
this.left = left;
this.right = right;
}
public int getVal() {
return val;
}
public void setVal(int val) {
this.val = val;
}
public Node getLeft() {
return left;
}
public void setLeft(Node left) {
this.left = left;
}
public Node getRight() {
return right;
}
public void setRight(Node right) {
this.right = right;
}
@Override
public String toString() {
return "Node{" +
"val=" + val +
'}';
}
}