/**
* 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) {
// Start typing your Java solution below
// DO NOT write main() function
if(root==null)return true;
return valid(root);
}
private boolean valid(TreeNode root){
if(root==null)return true;
int leftdep = height(root.left);
int rightdep = height(root.right);
boolean c = (leftdep-rightdep<=1&&leftdep-rightdep>=-1);
return c&&valid(root.left)&&valid(root.right);
}
private int height(TreeNode root){
if(root==null)return 0;
if(root.left==null&&root.right==null) return 1;
if(root.left==null)return height(root.right)+1;
if(root.right==null)return height(root.left)+1;
return Math.max(height(root.left),height(root.right))+1;
}
}
Balanced Binary Tree
最新推荐文章于 2023-04-13 15:01:12 发布