我已实现以下功能:
public int count(Node n) {
if (n == null) {
return 0;
} else if (n.left == null && n.right != null) {
return 1 + count(n.right);
} else if (n.left != null && n.right == null) {
return 1 + count(n.left);
}
return 0;
}
问题在于我用以下方式调用它:
System.out.println(tree.count(tree.root));
它只打印出root的值。我做错了什么?
答案 0 :(得分:2)
您的代码似乎包含实例方法和静态方法的元素,这有点令人困惑。选择一个,并在类似的方法中保持一致。最简单的方法是使用按位xor ^
(如果两个表达式中只有一个为true
),则返回true
这是static
方法。使用Node.countNonBranchingNodes(tree)
调用:
public static int countNonBranchingNodes(Node n) {
if (n == null) return 0;
return (n.left != null ^ n.right != null ? 1 : 0) +
countNonBranchingNodes(n.left) +
countNonBranchingNodes(n.right);
}
如果您需要实例方法版本,请使用tree.countNonBranchingNodes()
:
public int countNonBranchingNodes() {
int count = left != null ^ right != null ? 1 : 0;
if (left != null) count += left.countNonBranchingNodes();
if (right != null) count += right.countNonBranchingNodes();
return count;
}
答案 1 :(得分:1)
在您的代码中,您忘记处理具有左右子节点的节点,因此您的代码应该是这样的:
public int count(Node n) {
if (n == null) {
return 0;
} else if (n.left == null && n.right != null) {
return 1 + count(n.right);
} else if (n.left != null && n.right == null) {
return 1 + count(n.left);
} else {
return count(n.left) + count(n.right);
}
}
答案 2 :(得分:0)
在您的代码中,当节点同时拥有左右子项时,您还没有处理过这种情况。在这种情况下,我们必须避免对该节点进行计数,但仍然需要进一步继续计算左右子树。但是在你的解决方案中,如果节点同时拥有两个孩子,那么你只是返回0,那是不正确的。
public int countNodesWithExactlyOneChild(Node root){
if(root == null) return 0;
return (havingOneChild(root) ? 1 : 0) +
countNodesWithExactlyOneChild(root.left) +
countNodesWithExactlyOneChild(root.right);
}
private boolean havingOneChild(Node node) {
if(node != null && ((node.left == null && node.right != null) ||
(node.left != null && node.right == null))) {
return true;
}
return false;
}
答案 3 :(得分:0)
您的节点似乎有5种可能性:
"只剩下","仅限#34;,"左右和#34;,"左右都没有"和" null"。
public int count(Node n) {
// null
if (n == null) {
return 0;
// right only
} else if (n.left == null && n.right != null) {
return 1 + count(n.right);
// left only
} else if (n.left != null && n.right == null) {
return 1 + count(n.left);
// both left and right
} else if (n.left != null && n.right != null) {
return count(n.left) + count(n.right);
// neither left nor right
} else if (n.left == null && n.right == null) {
return 1;
// any else missing?
} else {
throw new RuntimeException();
}
}