LeetCode:110_Balanced Binary Tree | 平衡二叉树 | Easy

简介: 要求:判断一棵树是否是平衡二叉树 Given a binary tree, determine if it is height-balanced. For this problem, a height-balanced binary tree is defined as a binar...

要求:判断一棵树是否是平衡二叉树

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.
 

代码如下:

 1 struct TreeNode {
 2     int            val;
 3     TreeNode    *left;
 4     TreeNode    *right;
 5     TreeNode(int x): val(x),left(NULL), right(NULL) {}
 6 };
 7 
 8 int maxTreeDepth(TreeNode *root) //先求树的深度
 9 {
10     if (NULL == root)
11         return 0;
12     int lval = maxTreeDepth(root->left);
13     int rval = maxTreeDepth(root->right);
14     return 1 + (lval > rval ? lval:rval);
15 }
16 bool isBalanced(TreeNode *root)//根据树的深度再来判断是否是平衡树
17 {
18     if(NULL == root)
19         return true;
20     int diff = maxTreeDepth(root->left) - maxTreeDepth(root->right);
21     if (diff < -1 || diff > 1)
22         return false;
23     return isBalanced(root->left) && isBalanced(root->right);
24 }

 

目录
相关文章
|
12天前
【LeetCode 33】110.平衡二叉树
【LeetCode 33】110.平衡二叉树
8 1
|
5月前
leetcode代码记录(平衡二叉树
leetcode代码记录(平衡二叉树
34 0
|
2月前
|
算法 Java 关系型数据库
leetcode110-平衡二叉树
文章通过LeetCode第110题"平衡二叉树"的解题过程,深入讲解了平衡二叉树的定义、树的高度概念,并提供了使用后序遍历算法判断二叉树是否平衡的Java代码实现,强调了理解理论知识和实践编码的重要性。
|
2月前
|
Python
【Leetcode刷题Python】110. 平衡二叉树
LeetCode第110题"平衡二叉树"的Python解决方案,通过计算二叉树的高度并判断任意两个子树的高度差是否不超过1来确定树是否平衡。
17 2
|
4月前
|
SQL 算法 数据挖掘
力扣110:平衡二叉树
力扣110:平衡二叉树
|
11月前
|
算法
【LeetCode题目详解】(五)144.二叉树的前序遍历、94.二叉树的中序遍历、145.二叉树的后序遍历、104.二叉树的最大深度、110.平衡二叉树
【LeetCode题目详解】(五)144.二叉树的前序遍历、94.二叉树的中序遍历、145.二叉树的后序遍历、104.二叉树的最大深度、110.平衡二叉树
50 0
LeetCode | 110. 平衡二叉树
LeetCode | 110. 平衡二叉树
|
5月前
|
Java C++ Python
leetcode-110:平衡二叉树
leetcode-110:平衡二叉树
44 0
LeetCode刷题Day14——二叉树(完全二叉树、平衡二叉树、二叉树路径、左叶子之和)
一、完全二叉树的节点个数 题目链接:222. 完全二叉树的节点个数
|
11月前
|
算法
代码随想录算法训练营第十七天 | LeetCode 110. 平衡二叉树、257. 二叉树的所有路径、404. 左叶子之和
代码随想录算法训练营第十七天 | LeetCode 110. 平衡二叉树、257. 二叉树的所有路径、404. 左叶子之和
40 0