同時,也是一個有說法是私有的,這意味着我只能使用類似
MyBinaryTree bt = new MyBinaryTree();
int treeSize = bt.size();
通常代碼可以有意見,知道他們都是爲了。有時候乾淨的代碼甚至不需要評論。
/**
* Gets the size of the current binary tree.
*/
public int size() {
return(size(root));
}
/**
* Gets the size of the given branch
* @param node The branch to count from.
*/
private int size(Node node) {
if (node == null) return(0);
else {
return(size(node.left) + 1 + size(node.right));
}
}
從理論上講,在二叉樹中有子項的所有分支也可以作爲二叉樹處理。
![Binary Tree sample](https://i.stack.imgur.com/3ZUba.png)
注意size()
將調用第二個與根節點作爲參數,在這種情況下它意味着從A開始,在內部將是計數。
Size of the tree is count of items from A
Items from A are 1 + Items from B + Items from C
Items from B are 1
Items from C are 1 + Items from D + items from E
現在,爲什麼要使用method with the same name and diferent arguments?
可能有幾個理由去做或不去做。通常這意味着有多種方法可以做某些事情,或者您希望使用其他方式作爲默認方式,在這種情況下,size()將用作默認的根。