diff --git a/input.txt b/input.txt index 4858d6d..646ce06 100644 --- a/input.txt +++ b/input.txt @@ -1 +1 @@ -3,9,20,null,null,15,7 \ No newline at end of file +1,2,2,3,3,null,null,4,4 \ No newline at end of file diff --git a/src/com/dsa/trees/DepthFirstTraversal.java b/src/com/dsa/trees/DepthFirstTraversal.java index fa63168..183993a 100644 --- a/src/com/dsa/trees/DepthFirstTraversal.java +++ b/src/com/dsa/trees/DepthFirstTraversal.java @@ -4,7 +4,6 @@ import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.LinkedList; -import java.util.List; import java.util.Queue; public class DepthFirstTraversal { @@ -29,6 +28,7 @@ public class DepthFirstTraversal { index++; } System.out.println("MinDepth: " + minDepth(root)); + System.out.println("isBalanced: " + isBalanced(root)); } catch (IOException e) { throw new RuntimeException(e); } @@ -58,4 +58,18 @@ public class DepthFirstTraversal { if (rightHeight == 0) return leftHeight + 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; + } }