balanced tree check
This commit is contained in:
@@ -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;
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user