题解 | #判断是不是平衡二叉树#
判断是不是平衡二叉树
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;
}
// 计算左右子树的深度,深度超过1,则返回false
int left = deep(pRoot.left);
int right = deep(pRoot.right);
if (left - right > 1 || left - right < -1) {
return false;
}
// 分别判断左子树和右子树是否是平衡树
return IsBalanced_Solution(pRoot.left) && IsBalanced_Solution(pRoot.right);
}
/**
* 计算该子树深度
*/
public int deep(TreeNode node) {
if (node == null) {
return 0;
}
int left = deep(node.left);
int right = deep(node.right);
return left > right ? left + 1 : right + 1;
}
}
查看10道真题和解析