I have an assignment:
You’re given the root node of a binary tree T. We distinguish between 3 types of nodes in T: nodes with 0 children, nodes with 1 child, and nodes with 2 children. Determine, for each type, the number of nodes in T. Return your result as an integer array of length 3.
I am given a Java file that generates random test cases for this algorithm.
I am only allowed to create one function to do all of this. I am not allowed to pass any additional parameters into the method below. I am also not allowed to make any other modifications outside of the function that I create.
In the file, there is a base case already inserted. I have been told to traverse the tree in post-order, using recursion.
I am aware of the current issues with my code. But I don’t know how to fix them.
My current code is as follows:
private static int[] problem1(Node root) {
int[] arr = new int[3];
if (root == null) {
return new int[] {
-1, // nodes with 0 children
-1, // nodes with 1 child
-1 // nodes with 2 children
};
}
//problem1(root.left);
//problem1(root.right);
if (root.left != null && root.right != null) {
arr[2]++;
problem1(root.left);
problem1(root.right);
} else if (root.left != null && root.right == null) {
arr[1]++;
problem1(root.left);
} else if (root.left == null && root.right != null) {
arr[1]++;
problem1(root.right);
} else {
arr[0]++;
}
return arr;
}
The Node class is defined as:
static class Node {
public int value;
public Node left;
public Node right;
}