1
\$\begingroup\$

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.

asked Feb 3, 2022 at 15:11
\$\endgroup\$

2 Answers 2

1
\$\begingroup\$

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;
 }
answered Feb 5, 2022 at 21:10
\$\endgroup\$
2
  • \$\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\$ Commented 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\$ Commented Feb 11, 2022 at 12:43
2
\$\begingroup\$

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;
answered Feb 3, 2022 at 15:32
\$\endgroup\$
1
  • \$\begingroup\$ I have literally no experience with Ternary Operators, so I really have no idea what that code is meant to mean \$\endgroup\$ Commented Feb 3, 2022 at 16:30

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.