树的叶子节点数:
判断左右子数是否为空
为空即为叶子节点
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);
}
}
测试结果