一棵树是平衡的,是指该树的每个节点的左右子树的高度差不超过1。要判断一个由TreeNode构成的树是否平衡,可以通过递归的方式来判断每个节点的左右子树的高度差是否小于等于1。
具体步骤如下:
示例代码如下:
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
public class Solution {
public int getHeight(TreeNode node) {
if (node == null) {
return 0;
}
return Math.max(getHeight(node.left), getHeight(node.right)) + 1;
}
public boolean isBalanced(TreeNode node) {
if (node == null) {
return true;
}
int leftHeight = getHeight(node.left);
int rightHeight = getHeight(node.right);
if (Math.abs(leftHeight - rightHeight) > 1) {
return false;
}
return isBalanced(node.left) && isBalanced(node.right);
}
public static void main(String[] args) {
Solution solution = new Solution();
TreeNode root = new TreeNode(1);
root.left = new TreeNode(2);
root.right = new TreeNode(3);
root.left.left = new TreeNode(4);
root.left.right = new TreeNode(5);
boolean isBalanced = solution.isBalanced(root);
System.out.println("Is the tree balanced? " + isBalanced);
}
}
以上是用Java语言实现的判断树是否平衡的方法,其他编程语言也可根据相同的思路来实现。