我在这里有两个用于 size() 的函数,但它们看起来都像废话。第一个使用重载函数,第二个,你自己看看。我想做的是创建第二次尝试的精巧版本,但我的想法很低。
PS:告诉我使用 Java 的 util 有点毫无意义。我想让它漂亮,而不是隐藏它。
所以我的函数是从 BST 对象调用的,看起来像这样:
public int size() {
return size(root);
}
private int size(Node x) {
if (x == null) {
return 0;
} else {
return 1 + size(x.left) + size(x.right);
}
}
现在我不想重载函数,所以我重写了它:
public int size() {
Node y = root;
if (y == null) {
return 0;
} else {
root = y.left;
int left = size();
root = y.right;
int right = size();
root = y;
return 1 + left + right;
}
}
欢迎所有建议!