balanced tree check

This commit is contained in:
2026-06-18 11:47:09 +05:30
parent 3ca995f7ad
commit 989da02bf5
2 changed files with 16 additions and 2 deletions
+1 -1
View File
@@ -1 +1 @@
3,9,20,null,null,15,7 1,2,2,3,3,null,null,4,4
+15 -1
View File
@@ -4,7 +4,6 @@ import java.io.BufferedReader;
import java.io.FileReader; import java.io.FileReader;
import java.io.IOException; import java.io.IOException;
import java.util.LinkedList; import java.util.LinkedList;
import java.util.List;
import java.util.Queue; import java.util.Queue;
public class DepthFirstTraversal { public class DepthFirstTraversal {
@@ -29,6 +28,7 @@ public class DepthFirstTraversal {
index++; index++;
} }
System.out.println("MinDepth: " + minDepth(root)); System.out.println("MinDepth: " + minDepth(root));
System.out.println("isBalanced: " + isBalanced(root));
} catch (IOException e) { } catch (IOException e) {
throw new RuntimeException(e); throw new RuntimeException(e);
} }
@@ -58,4 +58,18 @@ public class DepthFirstTraversal {
if (rightHeight == 0) return leftHeight + 1; if (rightHeight == 0) return leftHeight + 1;
return Math.min(leftHeight, rightHeight) + 1; return Math.min(leftHeight, rightHeight) + 1;
} }
public static boolean isBalanced(TreeNode root) {
return balancedDepth(root) != -1;
}
public static int balancedDepth(TreeNode root) {
if (root == null) return 0;
int leftHeight = balancedDepth(root.left);
int rightHeight = balancedDepth(root.right);
if (leftHeight == -1 || rightHeight == -1) return -1;
int weight = Math.abs(leftHeight - rightHeight);
if (weight > 1) return -1;
return Math.max(leftHeight, rightHeight) + 1;
}
} }