import java.util.Scanner;
/**
* 求二叉树第n层节点个数
*
*/
public class GetBinaryTreeLevelN {
static class TreeNode {
public int value;
public TreeNode left;
public TreeNode right;
}
public static void createTree(TreeNode root) {
if (root == null) {
return;
}
System.out.println("输入" + root.value + "左右儿子的值:");
Scanner in = new Scanner(System.in);
int left = in.nextInt();
int right = in.nextInt();
if (left == 0) {
root.left = null;
} else {
TreeNode leftChild = new TreeNode();
leftChild.value = left;
root.left = leftChild;
}
if (right == 0) {
root.right = null;
} else {
TreeNode rightChild = new TreeNode();
rightChild.value = right;
root.right = rightChild;
}
createTree(root.left);
createTree(root.right);
}
public static int getNumInLevel(TreeNode root, int n) {
if (root == null || n <= 0)
return 0;
if (n == 1) {
return root == null ? 0 : 1;
}
int left = getNumInLevel(root.left, n - 1);
int right = getNumInLevel(root.right, n - 1);
return left + right;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
TreeNode root = new TreeNode();
root.value = 0;
createTree(root);
System.out.print("节点个数为:" + getNumInLevel(root, 3));
}
}