LeetCode110. Balanced Binary Tree(平衡二叉树)
程序员文章站
2022-05-18 19:38:51
...
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.
题目:判断是否是平衡二叉树。
思路:https://leetcode.com/problems/balanced-binary-tree/discuss/35691/The-bottom-up-O(N)-solution-would-be-better.左右子树的高度差不能超过1。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool isBalanced(TreeNode* root) {
return getDepth(root) != -1;
}
private:
int getDepth(TreeNode* root){
if(root == nullptr)
return 0;
int left = getDepth(root->left);
if(left == -1) return -1;
int right = getDepth(root->right);
if(right == -1) return -1;
if(abs(right-left) > 1)
return -1;
return 1 + max(right, left);
}
};
上一篇: 101. Symmetric Tree
下一篇: 基于tensorflow的图片数据处理
推荐阅读
-
21天刷题计划之17.1—maximum-depth-of-binary-tree(二叉树的最大深度)(Java语言描述)
-
21天刷题计划之18.1—balanced-binary-tree(平衡二叉树)(Java语言描述)
-
LeetCode 236 -- 二叉树的最近公共祖先 ( Lowest Common Ancestor of a Binary Tree ) ( C语言版 )
-
leetcode 235. Lowest Common Ancestor of a Binary Search Tree(二叉树的最低共同祖先)
-
平衡二叉树(Balanced Binary Tree 或 Height-Balanced Tree)又称AVL树
-
完全二叉树(Complete Binary Tree)或者完美二叉树(Perfect Binary Tree)中结点标号(label)与层数(level)的关系
-
第十章 ALDS1_9_A:Complete Binary Tree 完全二叉树
-
数据结构与算法1:二叉树(binary_tree)的前、中、后序(深度优先)和广度优先遍历及python代码实现
-
Tree_Graph 判断是否平衡二叉树 @CareerCup_PHP教程
-
Tree_Graph 判断是否平衡二叉树 @CareerCup_PHP教程