File tree Expand file tree Collapse file tree 1 file changed +56
-0
lines changed
src/main/java/com/thealgorithms/datastructures/trees Expand file tree Collapse file tree 1 file changed +56
-0
lines changed Original file line number Diff line number Diff line change 1+ package com.coding.patterns.tree;
2+
3+ class BalancedBinaryTree {
4+
5+ private static Pair<Boolean, Integer> dfs(TreeNode root) {
6+ if (root == null) {
7+ return new Pair<Boolean, Integer>(true, 0);
8+ }
9+
10+ var left = dfs(root.left);
11+ var right = dfs(root.right);
12+
13+ var balanced =
14+ left.getKey() &&
15+ right.getKey() &&
16+ (Math.abs(left.getValue() - right.getValue()) <= 1);
17+
18+ return new Pair<Boolean, Integer>(
19+ balanced,
20+ 1 + Math.max(left.getValue(), right.getValue())
21+ );
22+ }
23+
24+ public static boolean isBalanced(TreeNode root) {
25+ return dfs(root).getKey();
26+ }
27+ }
28+
29+ // Solution using the bottom up approach
30+ // TC and SC is On
31+
32+ class Solution {
33+
34+ public int height(TreeNode root){
35+ if(root == null){
36+ return 0;
37+ }
38+
39+ int lh = height(root.left);
40+ int rh = height(root.right);
41+
42+ return 1 + Math.max(lh,rh);
43+ }
44+
45+ public boolean isBalanced(TreeNode root) {
46+
47+ if(root == null){
48+ return true;
49+ }
50+
51+ int lh = height(root.left);
52+ int rh = height(root.right);
53+
54+ return Math.abs(lh - rh) <= 1 && isBalanced(root.left) && isBalanced(root.right);
55+ }
56+ }
You can’t perform that action at this time.
0 commit comments