开发者

Linked List size()

I need to implement a size() on these two classes and not really sure how to begin:

interface Tree extends Cloneable { 
    int size(); 
}

class Fruit implements Tree {

    @Override public int size() { 

    }
}

class Branch implements Tree {

    private List<Tree> children = new LinkedList<Tree>();
    public List<Tree> getChildren() { 
        return Collections.unmodifiableList(children); 
    }

  开发者_运维百科  public void addChild(Tree tree) { 
        children.add(tree); 
    }

    @Override public int size() { 

    }
}

Can anyone guide me in the right direction on how to create these two size() methods? I need them to calculates the number of actual fruits in a tree.


I assume this is homework? ;)

How about

@Override public int size() { 
    int size = 0;
    for(Tree tree: children) size += tree.size();
    return size;
}


Linked list operations are typically done in a recursive fashion, where every node has this definition for size:

@Override
public int size(){
     // Don't forget the base case! (if there is no child)
     return (child != null) ? 1 + child.size() : 1;
}

The call, rootNode.size(), recursively sums 1 for every node of the linked list and eventually returns size to the original caller.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜