Created
November 12, 2014 05:26
-
-
Save matthewrkula/d53139bd2e8080df60de to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Can't believe that's how easy it is... I thought too hard on how to calculate the depth of a tree node...