Skip to content

Instantly share code, notes, and snippets.

@jamilnyc
Created October 13, 2024 18:08
Show Gist options
  • Save jamilnyc/9c1ef1e05a755a9fc0c3779aa32d60ef to your computer and use it in GitHub Desktop.
Save jamilnyc/9c1ef1e05a755a9fc0c3779aa32d60ef to your computer and use it in GitHub Desktop.
public class TreeStats {
public int depth(Node root) {
if (root == null) {
return -1;
}
int leftDepth = depth(root.left);
int rightDepth = depth(root.right);
return Math.max(leftDepth, rightDepth) + 1;
}
public int maxValue(Node root) {
if (root == null) {
return Integer.MIN_VALUE;
}
int rootValue = root.value;
int leftValue = maxValue(root.left);
int rightValue = maxValue(root.right);
int max = rootValue;
if (leftValue > max) {
max = leftValue;
}
if (rightValue > max) {
max = rightValue;
}
return max;
}
public int minValue(Node root) {
if (root == null) {
return Integer.MAX_VALUE;
}
int rootValue = root.value;
int leftValue = maxValue(root.left);
int rightValue = maxValue(root.right);
int max = rootValue;
if (leftValue < max) {
max = leftValue;
}
if (rightValue < max) {
max = rightValue;
}
return max;
}
public int sum(Node root) {
if (root == null) {
return 0;
}
int leftSum = sum(root.left);
int rightSum = sum(root.right);
return leftSum + rightSum + root.value;
}
public int size(Node root) {
if (root == null) {
return 0;
}
return size(root.left) + size(root.right) + 1;
}
public int average(Node root) {
if (root == null) {
return 0;
}
return sum(root)/size(root);
}
public boolean isBalanced(Node root) {
// Empty subtree
if (root == null) {
return true;
}
// No children
if (root.left == null && root.right == null) {
return true;
}
boolean leftIsBalanced = isBalanced(root.left);
boolean rightIsBalanced = isBalanced(root.right);
if (!leftIsBalanced || !rightIsBalanced) {
return false;
}
int leftDepth = depth(root.left);
int rightDepth = depth(root.right);
return Math.abs(leftDepth - rightDepth) <= 1;
}
// https://www.geeksforgeeks.org/a-program-to-check-if-a-binary-tree-is-bst-or-not/
public boolean isBST(Node root) {
if (root == null) {
return true;
}
if (root.left != null && root.left.value > root.value) {
return false;
}
if (root.right != null && root.right.value < root.value) {
return false;
}
return isBST(root.left) && isBST(root.right);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment