Question
Solution
题目大意:判断一个二叉树是不是平衡二叉树
思路:定义个boolean来记录每个子节点是否平衡
Java实现:
public boolean isBalanced(TreeNode root) {
boolean[] balanced = {true};
height(root, balanced);
return balanced[0];
}
private int height(TreeNode node, boolean[] balanced) {
if (node == null) return 0;
int leftHeight = height(node.left, balanced);
int rightHeight = height(node.right, balanced);
balanced[0] = balanced[0] && !(Math.abs(leftHeight - rightHeight) > 1);
return balanced[0] ? Math.max(leftHeight, rightHeight) + 1 : -1;
}