-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathBT_Problem_14.java
More file actions
48 lines (37 loc) · 969 Bytes
/
Copy pathBT_Problem_14.java
File metadata and controls
48 lines (37 loc) · 969 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
package trees.binaryTree;
/*
* Problem Title :- Check if a tree is balanced or not
*/
public class BT_Problem_14 {
Node root;
boolean isBalanced(Node node) {
int lh;
int rh;
if(node == null)
return true;
lh = height(node.left);
rh = height(node.right);
if(Math.abs(lh - rh) <= 1 && isBalanced(node.left) && isBalanced(node.right)) {
return true;
}
return false;
}
int height(Node node) {
if(node == null)
return 0;
return 1 + Math.max(height(node.left), height(node.right));
}
public static void main(String[] args) {
BT_Problem_14 tree = new BT_Problem_14();
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.left.left.left = new Node(8);
if(tree.isBalanced(tree.root))
System.out.println("Tree is balanced");
else
System.out.println("Tree is not balanced");
}
}