2.二叉树的应用--二叉树的高度和叶子节点数

本文介绍了一种计算二叉树叶子节点数量和树高度的方法。通过递归算法,可以有效找出所有叶子节点并计算树的最大高度。代码示例展示了如何创建二叉树结构,遍历树并输出结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

树的叶子节点数:
判断左右子数是否为空
为空即为叶子节点

	public void showLeafNode() {
		if (leftNode == null && rightNode == null) {
			System.out.print(value);
		} else {
			leftNode.showLeafNode();
			rightNode.showLeafNode();
		}
	}

树的高度:
分别递归判断左子树和右子数
比较输出大的那个

public int treeHigh(Node root){
		if (root == null) {
			return 0;
		} else {
			int LH = 0;
			int RH = 0;
			int MaxH = 0;
			LH = treeHigh(root.leftNode);
			RH = treeHigh(root.rightNode);
			MaxH = LH > RH ? LH : RH;
			return MaxH + 1;
		}
	}

整体代码有点乱。。。。。

class Node{
	
	int value;
	Node leftNode;
	Node rightNode;
	
	public Node(int value) {
		this.value = value;
		leftNode = null;
		rightNode = null;
	}
	
	//设置左子树
	public void setLeftNode(Node leftNode) {
		this.leftNode = leftNode;
	}
	
	//设置右子数
	public void setRightNode(Node rightNode) {
		this.rightNode = rightNode;
	}
	
	//前序遍历
	public void frontShow() {
		System.out.print(value);
		if (leftNode != null) {
			leftNode.frontShow();
		}
		if (rightNode != null) {
			rightNode.frontShow();
		}
	}
	
	//输出叶子节点
	public void showLeafNode() {
		if (leftNode == null && rightNode == null) {
			System.out.print(value);
		} else {
			leftNode.showLeafNode();
			rightNode.showLeafNode();
		}
	}

}

class BinaryTree {
	
	Node root;
	
	public void setRoot(Node root) {
		this.root = root;
	}
	
	public void frontShow() {
		if (root != null) {
			root.frontShow();
		}
	}
	
	public void showLeafNode() {
		if (root != null) {
			root.showLeafNode();
		}
	}
	
	//树的高度
	public int treeHigh(Node root){
		if (root == null) {
			return 0;
		} else {
			int LH = 0;
			int RH = 0;
			int MaxH = 0;
			LH = treeHigh(root.leftNode);
			RH = treeHigh(root.rightNode);
			MaxH = LH > RH ? LH : RH;
			return MaxH + 1;
		}
	}
	
}

public class code03{	
	
	public static void main(String args[]) {
		BinaryTree B = new BinaryTree();
		Node root = new Node(0);
		B.setRoot(root);
		Node n1 = new Node(1);
		Node n2 = new Node(2);
		Node n3 = new Node(3);
		Node n4 = new Node(4);
		Node n5 = new Node(5);
		Node n6 = new Node(6);
		Node n7 = new Node(7);
		Node n8 = new Node(8);
		root.setLeftNode(n1);
		root.setRightNode(n2);
		n1.setLeftNode(n3);
		n1.setRightNode(n4);
		n2.setLeftNode(n5);
		n2.setRightNode(n6);
		n3.setLeftNode(n7);
		n3.setRightNode(n8);
		System.out.println("前序遍历是:");
		B.frontShow();
		System.out.println("");
		System.out.println("叶子节点是:");
		B.showLeafNode();
		System.out.println("");
		System.out.println("树的高度是:");
		int height = B.treeHigh(root);
		System.out.println(height);
	}
}

测试结果
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值