leecode 树的平衡判定 java

时间:2023-03-10 07:22:26
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; }
}