0

I have two functions here for size() but they both look like crap. The first one uses an overloaded function and the second, well, see for yourself. What I want to do is create a slick version of the second attempt but I'm low on ideas.

P.S: Telling me to use Java's util is kind of pointless. I want to make it pretty, not hide it.

So my function is called from a BST object and looks like this:

 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);
 }
 } 

Now I don't want to overload the function so I rewrote it as such:

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;
    }
}

All suggestions are welcome!

4

2 に答える 2

1

Nodeそれが定期的に呼び出されるものである場合、おそらくクラスのサイズをキャッシュし、挿入または削除するときに更新する方がよいでしょう。

public int size() {
    return root == null ? 0 : root.size();
}
于 2013-09-20T16:03:52.663 に答える
1

IMHO あなたの最初のアプローチで十分です。なんで?public size()BST のサイズの計算方法を管理する完全な public interface( ) があるため( を使用してprivate size())、内部実装を非表示にします。より良い設計上の決定につながる限り、オーバーロードに害はないと思います。

編集:これは、1番目のアプローチが2番目のアプローチよりも優れていることについての私の理解です。フィードバックを歓迎します。ありがとう!!

于 2013-09-20T16:07:05.480 に答える