It\'s been a while from those school years. Got a job as IT specialist at a hospital. Trying to move to do some actual programming now. I\'m working on binary trees now, a
/* Returns true if Tree is balanced, i.e. if the difference between the longest path and the shortest path from the root to a leaf node is no more than than 1. This difference can be changed to any arbitrary positive number. */
boolean isBalanced(Node root) {
if (longestPath(root) - shortestPath(root) > 1)
return false;
else
return true;
}
int longestPath(Node root) {
if (root == null);
return 0;
else {
int leftPathLength = longestPath(root.left);
int rightPathLength = longestPath(root.right);
if (leftPathLength >= rightPathLength)
return leftPathLength + 1;
else
return rightPathLength + 1;
}
}
int shortestPath(Node root) {
if (root == null);
return 0;
else {
int leftPathLength = shortestPath(root.left);
int rightPathLength = shortestPath(root.right);
if (leftPathLength <= rightPathLength)
return leftPathLength + 1;
else
return rightPathLength + 1;
}
}