题目描述
输入一棵二叉树,判断该二叉树是否是平衡二叉树。
题解
public class Solution {
public boolean IsBalanced_Solution(TreeNode root) {
if(root == null)
return true;
int m = depth(root.right) - depth(root.left);
if(m < -1 || m > 1)
return false;
return IsBalanced_Solution(root.left) && IsBalanced_Solution(root.right);
}
public int depth(TreeNode node) {
if(node == null)
return 0;
return Math.max(depth(node.left), depth(node.right)) + 1;
}
}
本文介绍了一种判断二叉树是否为平衡二叉树的方法,通过递归计算树的深度,比较左右子树深度差是否超过1来确定。平衡二叉树在数据结构和算法中有重要应用。
149

被折叠的 条评论
为什么被折叠?



