Google News
logo
Java program to determine whether all leaves are at same level
To determine whether all leaves are at the same level in a binary tree, we need to traverse the tree and keep track of the depth of the leaf nodes.

We can use a recursive approach to traverse the tree and check if all leaf nodes have the same depth.

Here's the Java code to determine whether all leaves are at the same level :
Program :
public class BinaryTree {

    static class Node {
        int data;
        Node left, right;
        
        public Node(int data) {
            this.data = data;
            this.left = null;
            this.right = null;
        }
    }
    
    Node root;
    
    public BinaryTree() {
        this.root = null;
    }
    
    // Utility function to determine the height of the tree
    public int height(Node node) {
        if (node == null) {
            return 0;
        } else {
            int leftHeight = height(node.left);
            int rightHeight = height(node.right);
            
            return Math.max(leftHeight, rightHeight) + 1;
        }
    }
    
    // Utility function to check if all leaves are at the same level
    public boolean checkLevel(Node node, int level, int leafLevel) {
        if (node == null) {
            return true;
        }
        
        // Check if current node is a leaf
        if (node.left == null && node.right == null) {
            // Check if leaf level has been set
            if (leafLevel == 0) {
                leafLevel = level;
            } else {
                // Check if leaf level is equal to current level
                if (level != leafLevel) {
                    return false;
                }
            }
        }
        
        return checkLevel(node.left, level + 1, leafLevel) && checkLevel(node.right, level + 1, leafLevel);
    }
    
    // Main function to check if all leaves are at the same level
    public boolean checkLeavesLevel() {
        int height = height(root);
        int leafLevel = 0;
        return checkLevel(root, 1, leafLevel);
    }
    
    // Testing the code
    public static void main(String[] args) {
        BinaryTree tree = new BinaryTree();
        tree.root = new Node(1);
        tree.root.left = new Node(2);
        tree.root.right = new Node(3);
        tree.root.left.left = new Node(4);
        tree.root.left.right = new Node(5);
        tree.root.right.left = new Node(6);
        tree.root.right.right = new Node(7);
        
        if (tree.checkLeavesLevel()) {
            System.out.println("All leaves are at the same level");
        } else {
            System.out.println("All leaves are not at the same level");
        }
    }
}
Output :
All leaves are at the same level