Program to check if a binary tree is height balanced or not

One comment on “Program to check if a binary tree is height balanced or not”


  • Zubair

    package com.company;

    import java.io.*;
    import java.lang.*;
    import java.util.*;

    public class Main {
    public static void main(String[] args) {
    abc tree =new abc();
    tree.add(8);
    tree.add(5);
    tree.add(9);

    System.out.println(tree.isbalanced(tree.root));
    }
    }
    class node {
    int data;
    node left;
    node right;

    public node(int data) {
    this.data = data;
    this.left=null;
    this.right=null;
    }
    }
    class abc{
    public node root=null;
    public node insert(node node ,int value){
    if (node==null){
    return new node(value);
    }
    else if (valuenode.data){
    node.right=insert(node.right,value);
    }
    return node;
    }
    public void add(int value){
    root =insert(root,value);
    }
    public boolean isbalanced(node node ){
    if (node==null){
    return true;
    }
    int lh =height(node.left);
    int rh =height(node.right);
    if (Math.abs(lh-rh)<=1&&isbalanced(node.left)&&isbalanced(node.right)){
    return true;
    }
    else {
    return false;
    }

    }
    static int height(node node){
    if (node==null){
    return 0;
    }
    else {
    return 1+Math.max(height(node.left),height(node.right));
    }
    }
    }