题解 | #判断是不是平衡二叉树#
判断是不是平衡二叉树
https://www.nowcoder.com/practice/8b3b95850edb4115918ecebdf1b4d222
/*class TreeNode {
* val: number
* left: TreeNode | null
* right: TreeNode | null
* constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
* }
*/
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
* @param pRoot TreeNode类
* @return bool布尔型
*/
export function IsBalanced_Solution(pRoot: TreeNode): boolean {
// write code here
if (pRoot === null) return true
const leftDeepth = deepth(pRoot.left)
const rightDeepth = deepth(pRoot.right)
if (Math.abs(leftDeepth - rightDeepth) >= 2) {
return false
} else {
return IsBalanced_Solution(pRoot.left) && IsBalanced_Solution(pRoot.right)
}
}
const deepth = (node: TreeNode): number => {
if (node === null) return 0
return 1 + Math.max(deepth(node.left), deepth(node.right))
}

