当前位置:网站首页>Leetcode 110. 平衡二叉树
Leetcode 110. 平衡二叉树
2022-07-23 01:34:00 【LuZhouShiLi】
Leetcode 110. 平衡二叉树
题目
给定一个二叉树,判断它是否是高度平衡的二叉树。
思路
- 明确递归函数的参数和返回值:参数是传入的节点指针,返回值是以该节点为根节点的二叉树的高度
- 明确终止条件:遇到空节点返回0,表示以当前节点为根节点的树高度是0
- 明确单层递归逻辑:判断左右子树高度之差,如果差值小于或者等于1,返回当前二叉树的高度
代码
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */
class Solution {
public:
// 返回以该节点为根节点的二叉树高度
int getDepth(TreeNode *node)
{
if(node == NULL)
{
return 0;
}
int leftDepth = getDepth(node->left);
if(leftDepth == -1)
{
return -1;// 说明左子树已经不是平衡二叉树
}
int rightDepth = getDepth(node->right);
if(rightDepth == -1)
{
return -1;// 说明右子树已经不是平衡二叉树
}
return abs(leftDepth - rightDepth) > 1 ? -1 : 1 + max(leftDepth,rightDepth);
}
bool isBalanced(TreeNode* root) {
return getDepth(root) == -1 ? false:true;
}
};
边栏推荐
- Wallys/PD-60 802.3AT Input Output802.3AT/AT 85% Efficiency 10/100/1000M GE Surge Protection
- Solve the greatest common divisor and the least common multiple
- A ConvNet for the 2020s 论文阅读
- 给我五分钟,给你一片“云”
- BCG 使用之CBCGPColorDialog控件
- 727. Minimum window subsequence sliding window
- BGP機房的優點
- 线性反馈移位寄存器(LSFR)
- Huawei applications have called the checkappupdate interface. Why is there no prompt for version update in the application
- Is it safe to buy shares and open an account? Will you lose money?
猜你喜欢

C语言实战之猜数游戏

FPGA出错的积累

Developers must see | devweekly issue 1: what is time complexity?

万物互联时代,看IoT测试如何应对“芯”挑战

肽核酸PNA-多肽suc-Ala-Ala-Pro-Aaa-pNa|Suc-Ala3-pNA|Pyr-Phe-Leu-pNA

Solve the greatest common divisor and the least common multiple
![[LeetCode]剑指 Offer 61. 扑克牌中的顺子](/img/ca/1756f1c33cf9b18d0c88d46bac636e.png)
[LeetCode]剑指 Offer 61. 扑克牌中的顺子

判斷是否為void類型

Program environment and pretreatment

服务器托管、服务器租用、云主机各自的优势
随机推荐
1646. Recursive method of getting the maximum value in the generated array
Server memory performance tuning
Transformer summary
网站建设开始前要考虑的7个问题
In the era of Internet of everything, see how IOT test meets the challenge of "core"
【FPGA教程案例36】通信案例6——基于vivado核的FFT傅里叶变换开发以及verilog输入时序配置详解,通过matlab进行辅助验证
作物叶片病害识别系统
Linear feedback shift register (lsfr)
Selenium.webdriver gets the result and converts it to JSON format
MATLAB之优劣解距离法Topsis模型
我是新手,听说开户有保本的理财产品,是什么?
判断是否为void类型
Go-Excelize API源码阅读(五)—— Close()、NewSheet()
Program environment and pretreatment
EasyV半年度“官方网站热门内容”排行榜盘点
正则表达式
详解Vector
AIRIOT答疑第5期|如何使用低代码业务流引擎?
transformer汇总
BeanSearcher接收数组参数、以及逻辑删除