110. Balanced Binary Tree(js)

110. 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.

Example 1:

Given the following tree [3,9,20,null,null,15,7]:

    3
   / \
  9  20
    /  \
   15   7

Return true.

Example 2:

Given the following tree [1,2,2,3,3,null,null,4,4]:

       1
      / \
     2   2
    / \
   3   3
  / \
 4   4

Return false.

题意:问给定的二叉树是不是平衡的二叉树(同属一个节点的子树高度相差不大于1)

代码如下:

扫描二维码关注公众号,回复: 5940623 查看本文章
/**
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */
/**
 * @param {TreeNode} root
 * @return {boolean}
 */
var isBalanced = function(root) {
    if(!root) return true;
    if(Math.abs(getDepth(root.left)-getDepth(root.right))>1) return false;
    return isBalanced(root.left) && isBalanced(root.right);
};
var getDepth=function(root){
    if(!root) return 0;
    return 1+Math.max(getDepth(root.left),getDepth(root.right));
}

猜你喜欢

转载自www.cnblogs.com/xingguozhiming/p/10732730.html
今日推荐