I have tried some methods but they dont have the right conditions for all cases.
Deque q=new LinkedList();
q.push(this.root);
while(!q.isEmpty()) {
Node nn=q.peekFirst();
System.out.print(nn.data+" ");
int size=q.size();
if(nn.left!=null) {
q.add(nn.left);
}
if(nn.right!=null) {
q.add(nn.right);
}
while(size>0) {
q.removeFirst();
size–;
}
}
What changes should I make?
How should I approach this question?
@Rishabh8488 so bro if you wish to do this by recursion you have to use an extra variable for level. here is the snippet, dry run for sample and you will be good to go.
if (root == null) {
return;
}
if(level > maxLevel[0]){
System.out.print(root.data+" ");
maxLevel[0] = level;
}
dfs(root.left, level + 1, maxLevel);
dfs(root.right, level + 1, maxLevel);
If ya doubt is cleared mark it resolved and rate full bro