package com.algorithm.charactor1;
import java.util.Random;
/**
*左迁堆,
*npl,为节点到子节点中没有两个节点的节点最短路径长,定义null节点的 npl为-1,叶子节点的npl为0
*
*左迁堆和null 合并的时候 返回 当前堆
*左迁堆的父节点的 小于 左右儿子节点
*节点的左儿子节点npl >= 右儿子节点npl
*节点的 npl =小儿子节点npl+1
*
*/
public class LeftHeap {
private Node root;
class Node{
private Node right;
private Node left;
private int npl = 0;//当前节点的最短路径长。
private Integer key ;
public Node(Node right, Node left, int npl, Integer key) {
super();
this.right = right;
this.left = left;
this.npl = npl;
this.key = key;
}
}
private void merge(LeftHeap other){
merge(this.root, other.root);
}
private Node merge(Node x, Node y) {
//当一个非空左迁堆和一个空 合并 返回 当前堆
if (x==null) {
return y;
}
if (y== null) {
return x;
}
//合并时,将x作为新的 根, 如果 x根大,则和y交换
if (x.key.compareTo(y.key) >=0) {
Node temp = x;
x =y;
y =temp;
}
//将x的
x.right = merge(x.right, y);
//如果的右节点为空,或者 右节点的npl,大于 左节点的时候
if (x.right == null || x.right.npl > x.left.npl) {
Node temp = x.right;
x.right= x.left;
x.left =temp;
}
if (x.right ==null ||x.left ==null) {
x.npl =0;
}else {
x.npl = x.left.npl> x.right.npl ? x.right.npl+1 :x.left.npl+1;
}
return x;
}
private void insert(Node node){
if (node!=null) {
this.root = merge(this.root, node);
}
}
public static void main(String[] args) {
LeftHeap leftHeap = new LeftHeap();
for (int i = 0; i < 10; i++) {
leftHeap.insert(leftHeap.new Node(null, null, 0, new Random().nextInt(10)));
}
}
}
java 左倾堆
最新推荐文章于 2024-01-28 20:15:02 发布