From ddf4265b783125529c9222b6c34caa747a4e3fe8 Mon Sep 17 00:00:00 2001 From: liuxiangyang Date: Mon, 12 Jul 2021 14:56:21 +0800 Subject: [PATCH] =?UTF-8?q?110.=20=E5=B9=B3=E8=A1=A1=E4=BA=8C=E5=8F=89?= =?UTF-8?q?=E6=A0=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...41\344\272\214\345\217\211\346\240\221.js" | 32 +++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 "110. \345\271\263\350\241\241\344\272\214\345\217\211\346\240\221.js" diff --git "a/110. \345\271\263\350\241\241\344\272\214\345\217\211\346\240\221.js" "b/110. \345\271\263\350\241\241\344\272\214\345\217\211\346\240\221.js" new file mode 100644 index 0000000..362f8b9 --- /dev/null +++ "b/110. \345\271\263\350\241\241\344\272\214\345\217\211\346\240\221.js" @@ -0,0 +1,32 @@ +/** + * 给定一个二叉树,判断它是否是高度平衡的二叉树。 + 本题中,一棵高度平衡二叉树定义为: + 一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1 。 + */ + +/** + * 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} + * 时间复杂度 O(n),空间复杂度 O(n) + */ +var isBalanced = function (root) { + return balanced(root) !== -1 +} + +function balanced(node) { + if (!node) return 0 + const left = balanced(node.left) + const right = balanced(node.right) + if (left === -1 || right === -1 || Math.abs(left - right) > 1) { + return -1 + } + return Math.max(left, right) + 1 +}