java 左倾堆

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)));
		}
		
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值