解题思路
看代码注释。
相关代码
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public boolean isBalanced(TreeNode root) {
//root表示递归时的此时的节点,如果为空节点,则为true
if(root==null) return true;
int l = dfs(root.left);
int r = dfs(root.right);
if(Math.abs(l-r)>1) return false;
//向下递归,判断左子树和右子树是否是平衡树。
return isBalanced(root.left)&&isBalanced(root.right);
}
//求出root节点到最下面的最大深度
public int dfs(TreeNode root){
if(root ==null) return 0;
return Math.max(dfs(root.left),dfs(root.right))+1;
}
}