Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // http://code2begin.blogspot.com
- // program to check if a given binary tree is a balanced binary tree or not
- /**
- * Created by MOHIT on 25-05-2018.
- */
- import java.io.*;
- import java.lang.reflect.Array;
- import java.util.*;
- import static java.lang.Integer.max;
- // node class
- class node{
- int data;
- node left;
- node right;
- // function that returns a pointer to new node
- public node(int element){
- this.data = element;
- this.left = null;
- this.right = null;
- }
- };
- public class BinaryTree {
- // function to find the height of a binary tree
- static int height(node root){
- if (root == null){
- return 0;
- }
- return (1 + max(height(root.left), height(root.right)));
- }
- // function to check if the tree is a height balanced tree or not
- static boolean isBalanced(node root){
- if(root == null){
- return true;
- }
- // get the heights of the left and the right subtrees
- int left_height = height(root.left);
- int right_height = height(root.right);
- // if the difference between heights of the left and right subtrees is less than 2
- // and left and right subtrees are also balanced then return true
- return Math.abs(left_height - right_height) <= 1 && isBalanced(root.left) && isBalanced(root.right);
- }
- public static void main(String arg[]) {
- // Binary Tree #1
- node head = new node(1);
- head.left = new node(2);
- head.right = new node(3);
- head.left.left = new node(4);
- head.left.right = new node(5);
- head.right.right = new node(6);
- head.left.left.right = new node(7);
- head.right.right.left = new node(8);
- head.left.left.right.left = new node(9);
- head.left.left.right.left.left = new node(10);
- head.right.right.left.right = new node(11);
- // Binary Tree #2
- node head2 = new node(5);
- head2.left = new node(2);
- head2.right = new node(12);
- head2.left.left = new node(-4);
- head2.left.right = new node(3);
- head2.right.left = new node(9);
- head2.right.right = new node(21);
- head2.right.right.left = new node(19);
- head2.right.right.right = new node(25);
- System.out.println("The Binary tree #1 is Balanced : " + isBalanced(head));
- System.out.println("The Binary tree #2 is Balanced : " + isBalanced(head2));
- }
- }
Add Comment
Please, Sign In to add comment