File tree Expand file tree Collapse file tree 1 file changed +40
-0
lines changed Expand file tree Collapse file tree 1 file changed +40
-0
lines changed Original file line number Diff line number Diff line change
1
+ import DS .TreeNode ;
2
+
3
+ /*
4
+ // Definition of TreeNode:
5
+ class TreeNode {
6
+ public int val;
7
+ public TreeNode left;
8
+ public TreeNode right;
9
+ public TreeNode(int val) {
10
+ this.val = val;
11
+ }
12
+ }
13
+ */
14
+
15
+ public class BalancedBinaryTreeValidation {
16
+ public boolean balancedBinaryTreeValidation (TreeNode root ) {
17
+ return getHeightImbalance (root ) != -1 ;
18
+ }
19
+
20
+ private int getHeightImbalance (TreeNode node ) {
21
+ // Base case: if the node is null, its height is 0.
22
+ if (node == null ) {
23
+ return 0 ;
24
+ }
25
+ // Recursively get the height of the left and right subtrees. If
26
+ // either subtree is imbalanced, propagate -1 up the tree.
27
+ int leftHeight = getHeightImbalance (node .left );
28
+ int rightHeight = getHeightImbalance (node .right );
29
+ if (leftHeight == -1 || rightHeight == -1 ) {
30
+ return -1 ;
31
+ }
32
+ // If the current node's subtree is imbalanced
33
+ // (height difference > 1), return -1.
34
+ if (Math .abs (leftHeight - rightHeight ) > 1 ) {
35
+ return -1 ;
36
+ }
37
+ // Return the height of the current subtree.
38
+ return 1 + Math .max (leftHeight , rightHeight );
39
+ }
40
+ }
You can’t perform that action at this time.
0 commit comments