Java实现二叉树的基本运算

Java实现二叉树的基本运算

public class BinTree01 {

	static int[] array = {1,2,3,4,5,6,7,8,9};
	static List<Node> nodelist = null;
	
	/*二叉树节点*/
	public static class Node {
		Node leftChirld;
		Node rightChirld;
		int data;
		public Node(int data) {
			leftChirld=null;
			rightChirld=null;
			this.data=data;
		}
	}
	
	/*构建二叉树*/
	public static void build() {
		nodelist=new LinkedList<Node>();
		
		for(int node=0;node<array.length;node++) {
			nodelist.add(new Node(array[node]));
		}
		
		for(int index=0;index<array.length/2-1;index++) {
			nodelist.get(index).leftChirld = nodelist.get(index*2+1);
			nodelist.get(index).rightChirld = nodelist.get(index*2+2);
			
		}
		
		int last = array.length/2-1;
		nodelist.get(last).leftChirld = nodelist.get(last*2+1);
		
		/*判断最后的节点是否有右孩子,有的话就进行添加*/
		if (array.length%2==1) {
			nodelist.get(last).rightChirld = nodelist.get(last*2+2);
		}

	}
	
	/*获取二叉树高度*/
	public static int getHeight(Node node) {
		int treeheight = 0;
		int leftheight = 0;
		int rightheight = 0;
		if (node!=null) {
			leftheight = getHeight(node.leftChirld);
			rightheight = getHeight(node.rightChirld);
			treeheight=leftheight>=rightheight?leftheight+1:rightheight+1;
			
		}
		return treeheight;
	}
	
	/*计算二叉树叶子节点个数*/
	public static int  getLeafCount(Node node) {
		int num1;
		int num2;
		if (node==null) {
			return 0;
		} else if (node.rightChirld==null && node.leftChirld==null) {
			return 1;
		} else {
			num1=getLeafCount(node.leftChirld);
			num2=getLeafCount(node.rightChirld);
			return num1+num2;
					
		}
			}
	
	/*计算节点个数*/
	public static int  getNodeCount(Node node) {
		int num1,num2;
		if (node==null) {
			return 0;
		} else {
			num1=getNodeCount(node.leftChirld);
			num2=getNodeCount(node.rightChirld);
			return num1+num2+1;
			
		}
	}
	
	
	
	
	
	public static void main(String[] args) {
			BinTree01 binTree01 = new BinTree01();
			binTree01.build();
			Node root = nodelist.get(0);
			System.out.println("节点个数:");
			System.out.println(binTree01.getNodeCount(root));
			System.out.println("");
			System.out.println("叶子节点");
			System.out.println(binTree01.getLeafCount(root));
			System.out.println("");
			
			System.out.println("高度");
			System.out.println(binTree01.getHeight(root));
	}

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值