Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.example.tree;
- import com.example.Node;
- // Tree is balanced when the difference between maximum and minimum height is <= 1.
- public class Tree{
- public static void main(String args[]){
- Node root = new Node();
- if(checkTreeBalance(root))
- System.out.println("Its a balanced tree");
- else
- System.out.println("Its not a balanced tree");
- }
- public static boolean checkTreeBalance(Node root){
- return (maxHeight(root) - minHeight(root)) <= 1 ;
- }
- public static int maxHeight(Node root){
- if(root == null)
- return 0;
- return 1 + Math.max(maxHeight(root.getLeft()),maxHeight(root.getRight()));
- }
- public static int minHeight(Node root){
- if(root == null)
- return 0;
- return 1 + Math.min(minHeight(root.getLeft()),minHeight(root.getRight()));
- }
- }
Add Comment
Please, Sign In to add comment