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。

解法:根据定义,只需要判定一颗二叉树的左右子树高度的高度差是否小于等于1。递归处理每一颗二叉树左右子树的高度,并进行判断再回溯。

Java:

class Solution {
int abs(int x) {
return x > 0 ? x : -x;
} int check(TreeNode* root) {
if (!root) return NULL; int lch = check(root -> left);
int rch = check(root -> right);
// 检查子树是否存在不平衡
if (lch == -1 || rch == -1 || abs(lch - rch) > 1) return -1; // 返回当前子树高度
return (lch > rch ? lch : rch) + 1;
}
public:
bool isBalanced(TreeNode* root) {
return check(root) != -1;
}
};  

Java:  without ResultType

public class Solution {
public boolean isBalanced(TreeNode root) {
return maxDepth(root) != -1;
} private int maxDepth(TreeNode root) {
if (root == null) {
return 0;
} int left = maxDepth(root.left);
int right = maxDepth(root.right);
if (left == -1 || right == -1 || Math.abs(left-right) > 1) {
return -1;
}
return Math.max(left, right) + 1;
}
} 

Python:

class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None class Solution:
# @param root, a tree node
# @return a boolean
def isBalanced(self, root):
return (self.getHeight(root) >= 0) def getHeight(self, root):
if root is None:
return 0
left_height, right_height = self.getHeight(root.left), self.getHeight(root.right)
if left_height < 0 or right_height < 0 or abs(left_height - right_height) > 1:
return -1
return max(left_height, right_height) + 1 

Python:

class Solution:
"""
@param root: The root of binary tree.
@return: True if this Binary tree is Balanced, or false.
"""
def isBalanced(self, root):
balanced, _ = self.validate(root)
return balanced def validate(self, root):
if root is None:
return True, 0 balanced, leftHeight = self.validate(root.left)
if not balanced:
return False, 0
balanced, rightHeight = self.validate(root.right)
if not balanced:
return False, 0 return abs(leftHeight - rightHeight) <= 1, max(leftHeight, rightHeight) + 1  

C++:

class Solution {
public:
bool isBalanced(TreeNode *root) {
if (!root) return true;
if (abs(getDepth(root->left) - getDepth(root->right)) > 1) return false;
return isBalanced(root->left) && isBalanced(root->right);
}
int getDepth(TreeNode *root) {
if (!root) return 0;
return 1 + max(getDepth(root->left), getDepth(root->right));
}
};

C++:

class Solution {
public:
bool isBalanced(TreeNode *root) {
if (checkDepth(root) == -1) return false;
else return true;
}
int checkDepth(TreeNode *root) {
if (!root) return 0;
int left = checkDepth(root->left);
if (left == -1) return -1;
int right = checkDepth(root->right);
if (right == -1) return -1;
int diff = abs(left - right);
if (diff > 1) return -1;
else return 1 + max(left, right);
}
};

C++:

/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
public:
int depth(TreeNode *root) {
if (root == NULL) {
return 0;
}
int left = depth(root->left);
int right = depth(root->right);
if (left == -1 || right == -1 || abs(left - right) > 1) {
return -1;
}
return max(left, right) + 1;
} /**
* @param root: The root of binary tree.
* @return: True if this Binary tree is Balanced, or false.
*/
bool isBalanced(TreeNode *root) {
return depth(root) != -1;
}
};

  

   

All LeetCode Questions List 题目汇总

[LeetCode] 110. Balanced Binary Tree 平衡二叉树的更多相关文章

  1. LeetCode 110. Balanced Binary Tree平衡二叉树 (C++)

    题目: Given a binary tree, determine if it is height-balanced. For this problem, a height-balanced bin ...

  2. C++版 - 剑指offer 面试题39:判断平衡二叉树(LeetCode 110. Balanced Binary Tree) 题解

    剑指offer 面试题39:判断平衡二叉树 提交网址:  http://www.nowcoder.com/practice/8b3b95850edb4115918ecebdf1b4d222?tpId= ...

  3. [LeetCode] 110. Balanced Binary Tree ☆(二叉树是否平衡)

    Balanced Binary Tree [数据结构和算法]全面剖析树的各类遍历方法 描述 解析 递归分别判断每个节点的左右子树 该题是Easy的原因是该题可以很容易的想到时间复杂度为O(n^2)的方 ...

  4. LeetCode 110. Balanced Binary Tree (平衡二叉树)

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

  5. LeetCode 110 Balanced Binary Tree(平衡二叉树)(*)

    翻译 给定一个二叉树,决定它是否是高度平衡的. (高度是名词不是形容词-- 对于这个问题.一个高度平衡二叉树被定义为: 这棵树的每一个节点的两个子树的深度差不能超过1. 原文 Given a bina ...

  6. LeetCode 110. Balanced Binary Tree(判断平衡二叉树)

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

  7. 【LeetCode】Balanced Binary Tree(平衡二叉树)

    这道题是LeetCode里的第110道题. 题目要求: 给定一个二叉树,判断它是否是高度平衡的二叉树. 本题中,一棵高度平衡二叉树定义为: 一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过1. ...

  8. LeetCode之Balanced Binary Tree 平衡二叉树

    判定一棵二叉树是不是二叉平衡树. 链接:https://oj.leetcode.com/problems/balanced-binary-tree/ 题目描述: Given a binary tree ...

  9. 110 Balanced Binary Tree 平衡二叉树

    给定一个二叉树,确定它是高度平衡的.对于这个问题,一棵高度平衡二叉树的定义是:一棵二叉树中每个节点的两个子树的深度相差不会超过 1.案例 1:给出二叉树 [3,9,20,null,null,15,7] ...

随机推荐

  1. 【Herding HDU - 4709 】【数学(利用叉乘计算三角形面积)】

    题意:给出n个点的坐标,问取出其中任意点围成的区域的最小值! 很明显,找到一个合适的三角形即可. #include<iostream> #include<cstdio> #in ...

  2. 使用python的jira库操作jira的版本单和问题单链接

    操作JIRA的API来实现的. 但感觉比单纯操作API要简单一些. from jira import JIRA from django.conf import settings JIRA_URL = ...

  3. treegrid 折叠全部节点

    $(".easyui-treegrid").treegrid({ url: '@Url.Action("GetDataDictionaryList", &quo ...

  4. 各大公司Java面试题收录含答案(整理版)持续中....

    本文分为17个模块,分别是:Java基础.容器.多线程.反射.对象拷贝.Java web.异常.网络.设计模式.算法.Spring/Spring MVC.Spring Boot/Spring Clou ...

  5. SQL操作Spark SQL--BasicSQLTestt

    object BasicSQLTest { def main(args: Array[String]): Unit = { val spark = SparkSession .builder() .a ...

  6. 学习Spring-Data-Jpa(十七)---对Web模块的支持

    Spring-Data还提供了Web模块的支持,这要求Web组件Spring-MVC的jar包位于classpath下.通常通过使用@EnableSpringDataWebSupport注解来启用继承 ...

  7. Linux grep 查找字符所在文件(grep详解)

    查找字符所在文件 grep -ir "S_ROLE"  ./* -i 不区分大小写 -r 查找字符出处 -a   --text   #不要忽略二进制的数据. -A<显示行数& ...

  8. BZOJ 5287: [Hnoi2018]毒瘤 动态dp(LCT+矩阵乘法)

    自己 yy 了一个动态 dp 做法,应该是全网唯一用 LCT 写的. code: #include <bits/stdc++.h> #define ll long long #define ...

  9. WinDbg的工作空间---Work Space

    一.什么是工作空间 Windbg把和调试相关的所有配置称为workspace.WinDbg使用工作空间来描述和存储调试项目的属性.参数及调试器设置等信息.工作空间与vc中的项目文件很相似.退出wind ...

  10. a list of frequently asked questions about Circus

    转自:https://circus.readthedocs.io/en/latest/faq/,可以帮助我们了解circus 的使用,以及问题解决 How does Circus stack comp ...