判断二叉树是否为一个平衡二叉树

见代码

1
2
3
4
5
6
7
8
9
10
11
12
13
const height = (node: TreeNode):number => {
if(node===null){
return 0;
}
return Math.max(height(node.left),height(node.right)) + 1;
}

function isBalanced(root: TreeNode | null): boolean {
if(root===null){
return true;
}
return Math.abs(height(root.left) - height(root.right)) <=1 && isBalanced(root.left) && isBalanced(root.right);
};