Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

110. 判断是否是平衡二叉树 #26

Closed
sailei1 opened this issue May 20, 2019 · 0 comments
Closed

110. 判断是否是平衡二叉树 #26

sailei1 opened this issue May 20, 2019 · 0 comments

Comments

@sailei1
Copy link
Owner

sailei1 commented May 20, 2019

给定一个二叉树,判断它是否是高度平衡的二叉树。

本题中,一棵高度平衡二叉树定义为:

一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过1。

示例 1:

给定二叉树 [3,9,20,null,null,15,7]

    3
   / \
  9  20
    /  \
   15   7

返回 true 。

示例 2:

给定二叉树 [1,2,2,3,3,null,null,4,4]

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

返回 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) {
       let rs=true; //默认平衡
      let findDepth=(node)=>{
         if(!node){return 0;}
          let left=findDepth(node.left); //获取左边最大深度
          let right=findDepth(node.right);// 获取后边最大深度
          if(Math.abs(left-right)>1){ //不平衡
              rs=false; 
          }
          return Math.max(left, right)+1;
      }
      findDepth(root);
    return rs;
     
      
};
@sailei1 sailei1 closed this as completed May 20, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant