- Notifications
You must be signed in to change notification settings - Fork24
Open
Labels
Description
一棵高度平衡二叉树定义为:一个二叉树每个节点的左右两个子树的高度差的绝对值不超过 1。
- 如果遍历完成,还没有高度差超过 1 的左右子树,则符合条件
- 判断左右子树高度差,超过 1 则返回 false
- 递归左右子树
- 封装获取子树高度函数 getHeight
constisBalanced=function(root){if(!root)returntrueif(Math.abs(getHeight(root.left)-getHeight(root.right))>1){returnfalse}returnisBalanced(root.left)&&isBalanced(root.right)functiongetHeight(root){if(!root)return0returnMath.max(getHeight(root.left),getHeight(root.right))+1}}
- 时间复杂度:O(n)
- 空间复杂度:O(n)