求二叉树的叶子节点数目,实现过程如下所示:
package cn.edu.nwu.structs.tree;
/**
* @author jcm
*
*时间 2016年9月3日
*/
public class GetLeafCount {
public static void main(String[] args) {
BinaryTreeNode root = CreateBinaryTree.createBinaryTree();
int count = getLeafCount(root);
System.out.println("叶子节点数目是"+count);
}
/**
* @author jcm
* @param root 树根
* @return 返回叶子节点个数
*/
public static int getLeafCount(BinaryTreeNode root){
if(root == null){
return 0;
}
if(root.leftTreeNode == null && root.rightTreeNode == null){
return 1;
}
int leftCount = getLeafCount(root.leftTreeNode);
int rightCount = getLeafCount(root.rightTreeNode);
return leftCount + rightCount;
}
}