Я пишу грубый код, проверьте, решает ли он вашу проблему:
HashMap<Integer, Integer> count = new HashMap<>();
//For now, 0 key having a count of leaf nodes, 1 key count of nodes having a single child, 2 for both
// Используйте inorder, pre или post для обхода дерева ... используйте countNodes, чтобы получить счет // I использовали hashmap для подсчета, вы также можете взять массив.
public void inorder(TreeNode root){
if(root == null) return;
inorder(root.left);
countNodes(root);
inorder(root.right);
}
public void countNodes(TreeNode root){
if(root == null) return;
else if(root.left != null && root.right != null){
count.put(2, 1 + count.getOrDefault(2,0));
}
else if(root.left == null && root.right == null){
count.put(0, 1 + count.getOrDefault(0,0));
}
else{
count.put(1, 1 + count.getOrDefault(1,0));
}
}