Ok so I am working on my algorithm and data structure knowledge and I am trying to find the largest number in each level of a binary tree. I am not sure what is wrong with my logic here.
class Solution
{
int maxLevel = 0;
public ArrayList<Integer> largestValues(Node root)
{
//code here
ArrayList<Integer> arr = new ArrayList<>();
checkHeight(root, 1, arr);
return arr;
}
void checkHeight(Node root, int height, ArrayList<Integer> arr){
if(root == null){
return;
}
if(maxLevel < height){
if(root.left != null && root.right != null){
arr.add(Math.max(root.left.data, root.right.data));
}
if(root.left != null && root.right == null){
arr.add(root.left.data);
}
if(root.left == null && root.right != null){
arr.add(root.right.data);
}
if(root.left == null && root.right == null){
return;
}
maxLevel = height;
}
checkHeight(root.left, height + 1, arr);
checkHeight(root.right, height + 1, arr);
}
}