Skip to content

Instantly share code, notes, and snippets.

@matthewrkula
Created November 12, 2014 05:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save matthewrkula/d53139bd2e8080df60de to your computer and use it in GitHub Desktop.
Save matthewrkula/d53139bd2e8080df60de to your computer and use it in GitHub Desktop.
public boolean isTreeBalanced(Node root) {
return (maxDepth(root) - minDepth(root)) <= 1;
}
public int maxDepth(Node root) {
if (root == null) {
return 0;
}
return 1 + Math.max(maxDepth(root.leftChild), maxDepth(root.rightChild));
}
public int minDepth(Node root) {
if (root == null) {
return 0;
}
return 1 + Math.min(minDepth(root.leftChild), minDepth(root.rightChild));
}
private class Node {
Node leftChild;
Node rightChild;
}
@YoungXiang
Copy link

Can't believe that's how easy it is... I thought too hard on how to calculate the depth of a tree node...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment