Hey @AbhishekAhlawat1102
Code is fine
Class Name must be Main:
updated code :
import java.util.*;
public class Main {
static Scanner scn = new Scanner(System.in);
public static void main(String[] args) {
Main m = new Main();
BinaryTree bt = m.new BinaryTree();
System.out.println(bt.isBalanced());
}
private class BinaryTree {
private class Node {
int data;
Node left;
Node right;
}
private Node root;
private int size;
public BinaryTree() {
this.root = this.takeInput(null, false);
}
public Node takeInput(Node parent, boolean ilc) {
int cdata = scn.nextInt();
Node child = new Node();
child.data = cdata;
this.size++;
// left
boolean hlc = scn.nextBoolean();
if (hlc) {
child.left = this.takeInput(child, true);
}
// right
boolean hrc = scn.nextBoolean();
if (hrc) {
child.right = this.takeInput(child, false);
}
// return
return child;
}
public boolean isBalanced() {
return this.isBalanced(this.root).isBalanced;
}
private BalancedPair isBalanced(Node node) {
if(node == null){
BalancedPair bp = new BalancedPair(-1, true);
return bp;
}
BalancedPair lb = this.isBalanced(node.left);
BalancedPair rb = this.isBalanced(node.right);
BalancedPair bm = new BalancedPair();
bm.height = Math.max(lb.height, rb.height) + 1;
int diff = Math.abs(lb.height - rb.height);
bm.isBalanced = (diff <= 1 && lb.isBalanced && rb.isBalanced);
return bm;
}
private class BalancedPair {
int height;
boolean isBalanced;
BalancedPair(){
}
BalancedPair(int h, boolean flag){
this.height = h;
this.isBalanced = flag;
}
}
}
}