题解 | #判断是不是平衡二叉树# 递归 + 状态记录
判断是不是平衡二叉树
https://www.nowcoder.com/practice/8b3b95850edb4115918ecebdf1b4d222
import java.util.*;
/*
* public class TreeNode {
* int val = 0;
* TreeNode left = null;
* TreeNode right = null;
* public TreeNode(int val) {
* this.val = val;
* }
* }
*/
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param pRoot TreeNode类
* @return bool布尔型
*/
public boolean IsBalanced_Solution (TreeNode pRoot) {
if(pRoot == null) return true;
int lDepth = getDepth(pRoot.left);
int rDepth = getDepth(pRoot.right);
if(lDepth == -1 || rDepth == -1) return false;
if(Math.abs(lDepth - rDepth) > 1) return false;
return true;
}
public int getDepth(TreeNode root){
if(root == null) return 0;
int lDepth = getDepth(root.left);
int rDepth = getDepth(root.right);
// 不平衡条件
if(Math.abs(lDepth - rDepth) > 1) return -1;
if(lDepth == -1 || rDepth == -1) return -1;
return 1 + Math.max(lDepth,rDepth);
}
}
在任意一个子树发生不平衡,则整个平衡树即不成立,计算深度不平衡,则一直向最上层递归传递 -1
查看5道真题和解析