
Java中如何实现返回二叉树中存储着偶数的分支节点数?图中的代码又应该如何补全?
//假设IntTreeNode的结构如下
class IntTreeNode {
int val;//值
IntTreeNode left;//左子树
IntTreeNode right;//右子树
public IntTreeNode(int val) {
this.val = val;
}
}
//补全后的代码
private int countEvenBranches(IntTreeNode root) {
if (root == null || root.left == null && root.right == null && root.val % 2 != 0) {
return 0;
} else {
int result = 0;
if (root.val % 2 == 0) {
result = 1;
}
return result + countEvenBranches(root.left) + countEvenBranches(root.right);
}
}
public class Web_02_countEvenBranches {
public static void main(String[] args) {
TreeNode tree = TreeNode.createTree();
TreeNode.printTree(tree);
int i = countEvenBranches(tree);
System.out.println(i);
}
//递归求解
private static int countEvenBranches(TreeNode root) {
//不满足条件直接返回
if (root == null || root.left == null && root.right == null && root.val % 2 != 0) {
return 0;
} else {
//返回当前节点的result
int result = 0;
//满足
if (root.val % 2 == 0) {
result = 1;
}
//根节点+左右节点
return result + countEvenBranches(root.left) + countEvenBranches(root.right);
}
}
}