java哈夫曼树的生成

简单测试,写的有点差

package com.dong;

import java.util.ArrayList;

class tree{
//	先序遍历,根左右
	static void pro(Node root) {
		if(root!=null) {
			System.out.print(root.data+",");
			pro(root.left);
			pro(root.right);
		}
	}
//	中序遍历,左根右
	static void mid(Node root) {
		if(root!=null) {
			mid(root.left);
			System.out.print(root.data);
			mid(root.right);
		}
	}
//	后续遍历,左右根
	static void last(Node root) {
		if(root!=null) {
			
			last(root.left);
			last(root.right);
			System.out.print(root.data);
		}
	}
}
class Node {
//	存储的数据类型为Sting类型
	String data;
	Node left=null;
	Node right=null;
	void Node(String data,Node left,Node right) {
		this.data=data;
		this.left=left;
		this.right=right;
		
	}	
}

public class Test {
	public static void main(String[] args) {
//		创捷节点对象
		Node node5 = new Node();
		Node node4 = new Node();
		Node node3 = new Node();
		Node node2 = new Node();
		Node node1 = new Node();
		ArrayList<Integer> list = new ArrayList<Integer>();	
		list.add(4);
		list.add(2);
		list.add(6);	
//		-----------生成 24
		list.sort(null);
		list.add(list.get(0)+list.get(1));
		node1.Node(list.get(1).toString(), null, null);	
		node2.Node(list.get(0).toString(), null, null);
	
		list.remove(0);
		list.remove(0);
//		--------------------------------------
		list.sort(null);
		list.add(list.get(0)+list.get(1));
		node3.Node(list.get(0).toString(), node2, node1);
		node4.Node(list.get(1).toString(), null, null);	
//		-------------------------------------
		node5.Node(Integer.toString(list.get(1).intValue()+list.get(0).intValue()), node3, node4);	
		System.out.println("先序:");
		tree.pro(node5);

		

		
	}
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值