leecode 树的平衡判定 java

以前写过c++版本的,感觉java写的好舒心啊
/** * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public boolean isBalanced(TreeNode root) { if(root==null) return true; if(Math.abs(depth(root.left)-depth(root.right))<=1) { return isBalanced(root.left)&&isBalanced(root.right); } else { return false; } } public int depth(TreeNode tn) { if(tn==null) return 0; int le=depth(tn.left); int rl=depth(tn.right); if(le>=rl) return le+1; else return rl+1; } }

  

posted @ 2014-06-29 15:21  hansongjiang8  阅读(161)  评论(0编辑  收藏  举报