I am currently taking a Data Structures and Algorithms course. Last class, my Professor put up some code on the board to explain how to write the size()
, the height()
, and left()
/right()
methods to teach us two-balance in anticipation for a quiz.
He wrote the code you see below on the board, but he mentioned that while he made an error, to focus on the logic for now and that he would have to run a few tests to understand his error.
public class BT<T> {
TreeNode<T> root;
BT<T> myTree;
//size
public int size() {
if(this.isEmpty())
return 0;
return (1 + this.left().size() + this.right().size());
}
//isEmpty()
public boolean isEmpty() {
return (root == null);
}
//left
public BT<T> left() {
return root.left;
}
public BT<T> right() {
return root.right;
}
}
Over the weekend, I tried to figure this out myself, as during my Professor's office hours, he wasn't able to work on the code due to the high volume of students visiting him in regards to the midterm.
What's the way to fix this method?
EDIT:
Here's the TreeNode<T>
class
class TreeNode<T> {
T data;
TreeNode<T> left;
TreeNode<T> right;
}
It was inside another class within the same package.