# 二叉树 求叶子节点数并返回叶子节点个数

Java版数据结构 专栏收录该内容
2 篇文章 0 订阅

package com.alibaba.structure.school.two;

// 节点类
public class BinaryNode<T> {

public T data;
public BinaryNode<T> left,right;

// 构造节点
public BinaryNode(T data,BinaryNode<T> left,BinaryNode<T> right){
this.data = data;
this.left = left;
this.right = right;
}

public BinaryNode(T data){
this(data,null,null);   // this构造方法
}

public String toString(){                   // 返回节点数据域的描述字符串
return this.data.toString();
}

public boolean isLeaf(){
return this.left == null && this.right == null;
}

}

package com.alibaba.structure.school.two;

// 二叉树类
public class BinaryTree<T> {

public BinaryNode<T> root;   // 根节点

public boolean isEmpty() {    // 判断二叉树是否为空
return this.root == null;
}

public BinaryTree(T[] prelist) {    // 初始的时候构造二叉树
this.root = create(prelist);
}

private int i = 0;
private BinaryNode<T> create(T[] prelist) {  // {"A","B","D",null,"G",null,null,null,"C","E",null,null,"F","H"};
BinaryNode<T> p = null;
if (i < prelist.length) {
T elem = prelist[i];
i++;
if (elem != null) {
p = new BinaryNode<T>(elem);
p.left = create(prelist);
p.right = create(prelist);
}
}
return p;
}

int sum = 0;
public void preorder(){     // 孩子节点优先遍历 ( 先根 )
int sum = preorder(this.root);
System.out.println("叶子节点总数为：" + sum);
}

private int preorder(BinaryNode<T> p){
if(p != null){
if(p.isLeaf()){
sum +=1;
System.out.println(p.data.toString() + " ");
}
preorder(p.left);
preorder(p.right);
}
return sum;
}

public String toString() {
}

private String toString(BinaryNode<T> p) {      // ^ : 表示空
if (p == null)
return "^" + " ";
return p.data.toString() + " " + toString(p.left) + toString(p.right);
}
}


Main方法：

package com.alibaba.structure.school.two;

// 求叶子节点的个数，并且打印输出叶子节点
public class Main {

public static void main(String[] args) {
/*
A
/   \
B     C
/ \  /  \
D  ^ E    F
/ \  / \  / \
^  G ^  ^ H   ^
/ \    / \
^  ^   ^   ^

*/
//        String [] prelist = {};
//        String [] prelist = {"A"};
String [] prelist = {"A","B","D",null,"G",null,null,null,"C","E",null,null,"F","H"};
BinaryTree<String> bitree = new BinaryTree<>(prelist);
System.out.println("前序遍历：" +  bitree.toString());  // 中 左 右

bitree.preorder();  // 返回叶子结点和总和
}
}

• 0
点赞
• 1
评论
• 2
收藏
• 一键三连
• 扫一扫，分享海报

10-19 3797
02-06 2384
11-04 2132
09-07 2047
07-21 110
03-06 4927
06-05 46
12-21 6004
11-24 108
09-30 3393
12-01 2万+
©️2021 CSDN 皮肤主题: 大白 设计师:CSDN官方博客

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