This is my size method for my binary search tree, that is meant to implement recursion to calculate the tree's size.
public int size() {
if (left != null && right != null) {
return left.size() + 1 + right.size();
}
else if (left != null && right == null) {
return left.size() + 1;
}
else if (right != null && left == null) {
return right.size() + 1;
}
else {
return 0;
}
}
First I'm wondering if this looks all right. I also got some feedback on this function that I can calculate the size of the tree with fewer if statements but I don't see how I can do that.
2 Answers 2
Can be made much simpler:
public int size() {
int size=1;
if(left != null) size+=left.size();
if(right != null) size+=right.size();
return size;
}
-
\$\begingroup\$ This does assume that if left and right are both null the size is also 1 where OP's code would return 0. Might have been a bug in OP's code. \$\endgroup\$Imus– Imus2022年02月11日 12:19:18 +00:00Commented Feb 11, 2022 at 12:19
-
\$\begingroup\$ @Imus Defenetly a bug in OP's code, as you need to have at least 1 node to be able to call size(). \$\endgroup\$convert– convert2022年02月11日 12:43:13 +00:00Commented Feb 11, 2022 at 12:43
Seems strange for the else
case to return zero. I would expect it to return 1 (the node itself).
Then it becomes much simpler:
int leftSize = left == null ? 0 : left.size();
int rightSize = right == null ? 0 : right.size();
return 1 + leftSize + rightSize;
-
\$\begingroup\$ I have literally no experience with Ternary Operators, so I really have no idea what that code is meant to mean \$\endgroup\$Rasmus Steen– Rasmus Steen2022年02月03日 16:30:48 +00:00Commented Feb 3, 2022 at 16:30