Reputation: 33
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);
}
}
Upvotes: 1
Views: 899
Reputation: 6808
It appears that you are not familiar with what largest number in each level of a binary tree means. Your current implementation takes the largest of the left and right children of a node and if it only has one child then that child.
A level in a binary tree consists of all the nodes that have the same depth regardless of whether they are immediate children of the same parent or not.
Therefor you algorithm is fundamentally wrong.
There are 2 approaches to solve this problem: DFS and BFS.
BFS is more straight forward, or it appears to me at least. Here's how it goes:
DFS works as follows:
Upvotes: 3