`class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int val) {
this.val = val;
this.left = null;
this.right = null;
}
}
class BinaryTree {
public static int countNodesWithDegreeOne(TreeNode root) {
if (root == null) {
return 0;
}
int leftCount = countNodesWithDegreeOne(root.left);
int rightCount = countNodesWithDegreeOne(root.right);
int degree = (root.left!= null? 1 : 0) + (root.right!= null? 1 : 0);
if (degree == 1) {
return leftCount + rightCount + 1;
} else {
return leftCount + rightCount;
}
}
}`
public class Main {
public static void main(String[] args) {
TreeNode root = new TreeNode(1);
root.left = new TreeNode(2);
root.right = new TreeNode(3);
root.left.right = new TreeNode(4);
int count = BinaryTree.countNodesWithDegreeOne(root);
System.out.println("度为 1 的结点个数为:" + count);
}
}
标签:结点,中度,TreeNode,int,right,二叉树,null,root,left From: https://www.cnblogs.com/zyh-828/p/18493720