12 Balanced Binary Tree 平衡二叉树计算

67 阅读1分钟

leetcode.cn/problems/ba…

关键就是计算一棵树的高度计算 还有就是递归的去判断 左右节点是否是 isBalanced

解题思路

  1. 如果不存在节点,直接返回 true
  2. 递归计算节点 left right depth 深度,如果绝对值不大于 1则认为这个节点是 height-balanced
  3. 递归计算 left right 节点是否是 height-balanced,如果是则认为是 height-balanced

代码

/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {boolean}
 */
var depth = (node) => {
    if(node == null) return 0
    return Math.max(depth(node.left), depth(node.right)) + 1
}
var isBalanced = function(root) {
    if(root == null) return true
    let leftDepth = depth(root.left)
    let rightDepth = depth(root.right)
    return Math.abs(leftDepth - rightDepth) <= 1 && isBalanced(root.left) && isBalanced(root.right)
};