Advertisement
tanglinghui

ctciCh4Q1

Jun 17th, 2012
215
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.49 KB | None | 0 0
  1.     public boolean isBalanced() {
  2.         return checkHeight(this.root) == -1 ? false : true;
  3.     }
  4.  
  5.     private int checkHeight(TreeNode node) {
  6.         if(node == null){
  7.             return 0;
  8.         }
  9.         int leftHeight = checkHeight(node.leftChild);
  10.         if (leftHeight == -1) {
  11.             return -1;
  12.         }
  13.         int rightHeight = checkHeight(node.rightChild);
  14.         if (rightHeight == -1) {
  15.             return -1;
  16.         }
  17.  
  18.         if (Math.abs(leftHeight - rightHeight) > 1) {
  19.             return -1;
  20.         } else {
  21.             return Math.max(leftHeight, rightHeight)+1;
  22.         }
  23.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement