[LeetCode][JavaScript]Balanced Binary Tree

Balanced Binary Tree

Given a binary tree, determine if it is height-balanced.

For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.

https://leetcode.com/problems/balanced-binary-tree/


判断给的数是不是平衡二叉树,平衡的定义是指任意节点的左右子树高度相差不超过1。

一个递归方法,返回树的高度,如果左右子树高度相差超过1则返回-1。

 1 /**
 2  * Definition for a binary tree node.
 3  * function TreeNode(val) {
 4  *     this.val = val;
 5  *     this.left = this.right = null;
 6  * }
 7  */
 8 /**
 9  * @param {TreeNode} root
10  * @return {boolean}
11  */
12 var isBalanced = function(root) {
13     return treeHeight(root) === -1 ? false : true;
14 
15     /**
16      * @return {int} tree's height
17      * return -1 if depth differ of the two subtrees are more than 1
18      */
19     function treeHeight(node){
20         if(node === null) return 0;
21         if(node.left === null && node.right === null) return 1;
22         var leftH = treeHeight(node.left);
23         var rightH = treeHeight(node.right);
24         if(leftH === -1 || rightH === -1) return -1;
25         if(Math.abs(leftH - rightH) > 1) return -1;
26         return Math.max(leftH, rightH) + 1;
27     }
28 };
原文地址:https://www.cnblogs.com/Liok3187/p/5092327.html