zoukankan      html  css  js  c++  java
  • 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)

    代码如下:

    /**
     * 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));
    }
  • 相关阅读:
    jQ的工具类方法
    jq-ajax
    jq-ajax-get
    LOAD
    JQ的尺寸类
    JQ-DOM与元素的操作
    jQ-DOM属性的操作
    jQ的事件
    3位创业公司CEO亲述:200人的小公司,这么做数据管理就对了
    十二潜意识的智商
  • 原文地址:https://www.cnblogs.com/xingguozhiming/p/10732730.html
Copyright © 2011-2022 走看看