以前写过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; } }
leecode 树的平衡判定 java
时间: 2024-10-15 03:48:10