题目描述:
输入一棵二叉树,判断该二叉树是否是平衡二叉树
思路:
根据平衡二叉树的特性:平衡因子的绝对值 <= 1。
因此,本题的重点应在于求解左子树、右子树的深度。
代码实现:
public class Solution {
public boolean IsBalanced_Solution(TreeNode root) {
if (root == null) {
return true;
}
int left = getDepth(root.left);
int right = getDepth(root.right);
// 求左右子树的差值
int diff = left - right;
if ((diff >= -1) && (diff <= 1)) {
return true;
}
return false;
}
public int getDepth(TreeNode root) {
// 边界条件,达到叶子节点
if (root == null) {
return 0;
}
int depth = 0;
// 迭代求左子树深度
int leftNode = getDepth(root.left);
// 迭代右子树深度
int rightNode = getDepth(root.right);
// 该树左右子树中的最大值 +1 为该树的深度
depth = leftNode > rightNode ? leftNode : rightNode;
return depth + 1;
}
}