I have written this code for checking whether all leaves are in the same level or not, in a binary tree. Any suggestion or improvement is appreciated.
import java.util.LinkedList;
import java.util.Queue;
public class Methods {
//* ---- Method for check whether all leaves are in the same level or not --- *
public static boolean leavesIn1Level(Node root){
if(root == null){
return false;
}
if(root.left == null && root.right == null){
return true;
}
Queue<Node> q = new LinkedList<Node>();
q.add(root);
int levelNumber = 0;
int height = height(root);
while(true){
int nodeCount = q.size();
if(nodeCount == 0){
break;
}
while(nodeCount > 0){
Node current = q.remove();
nodeCount--;
if(current.left == null && current.right == null){
if(height != levelNumber){
return false;
}else{
return true;
}
}
if(current.left != null){
q.add(current.left);
}
if(current.right != null){
q.add(current.right);
}
}
levelNumber++;
}
return false;
}
//* ---- Method for finding height of a binary tree ---- *
public static int height(Node root){
if(root == null){
return -1;
}else{
return Math.max(height(root.left), height(root.right))+1;
}
}
public static void main(String[] args) {
Node root1 = new Node(8); // 8
root1.left = new Node(9); // / \
root1.right = new Node(5); // 9 5
root1.left.left = new Node(4); // / /
root1.right.left = new Node(1); // 4 1
root1.right.left.left = new Node(3); // /
root1.right.left.left.left = new Node(2); // 3
// /
// 2
Node root2 = new Node(1); // 1
root2.left = new Node(2); // / \
root2.right = new Node(3); // 2 3
root2.left.left = new Node(4); // / \ /
root2.left.right = new Node(5); // 4 5 6
root2.right.left = new Node(6);
System.out.println(leavesIn1Level(root1));
System.out.println(leavesIn1Level(root2));
}
}
Node
class:
public class Node {
int data;
Node left;
Node right;
public Node(int d){
data = d;
left = null;
right = null;
}
}
This code is different from: Check if all leaves are at same level