[英]how to count the number of nodes in a binary tree with only one child?
我已经实现了以下功能:
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));
它仅显示根的值。 我究竟做错了什么?
您的代码似乎同时具有实例方法和静态方法的元素,这有点令人困惑。 选择一个,并在类似方法中保持一致。 最简单的方法是使用按位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;
}
在您的代码中,您忘记处理左右两个子节点,因此您的代码应如下所示:
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);
}
}
在您的代码中,您没有处理节点同时具有左右两个子节点的情况。 在那种情况下,我们必须避免对该节点进行计数,但是仍然必须继续进行左右子树的计数。 但是在您的解决方案中,如果节点同时拥有两个孩子,那么您只是返回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;
}
看来您的节点将有5种可能性:
“仅左”,“仅右”,“左右”,“左右都不”和“空”。
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();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.