Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 74c6ec9

Browse files
add LeetCode 110. 平衡二叉树
1 parent 9116dde commit 74c6ec9

File tree

1 file changed

+99
-0
lines changed

1 file changed

+99
-0
lines changed
Lines changed: 99 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,99 @@
1+
![](https://imgconvert.csdnimg.cn/aHR0cHM6Ly9jZG4uanNkZWxpdnIubmV0L2doL2Nob2NvbGF0ZTE5OTkvY2RuL2ltZy8yMDIwMDgyODE0NTUyMS5qcGc?x-oss-process=image/format,png)
2+
>仰望星空的人,不应该被嘲笑
3+
4+
## 题目描述
5+
6+
给定一个二叉树,判断它是否是高度平衡的二叉树。
7+
8+
本题中,一棵高度平衡二叉树定义为:
9+
10+
一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过1。
11+
12+
示例 1:
13+
14+
```javascript
15+
给定二叉树 [3,9,20,null,null,15,7]
16+
17+
3
18+
/ \
19+
9 20
20+
/ \
21+
15 7
22+
返回 true
23+
```
24+
25+
示例 2:
26+
27+
```javascript
28+
给定二叉树 [1,2,2,3,3,null,null,4,4]
29+
30+
1
31+
/ \
32+
2 2
33+
/ \
34+
3 3
35+
/ \
36+
4 4
37+
返回 false
38+
```
39+
40+
来源:力扣(LeetCode)
41+
链接:https://leetcode-cn.com/problems/balanced-binary-tree
42+
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
43+
44+
45+
46+
## 解题思路
47+
`dfs`,平衡二叉树就是每个节点 的左右两个子树的高度差的绝对值不超过1。那么,我们可以自底向上,即采用后序遍历的方式,只要左右高度超过1了,直接设置 `flase`即可。
48+
49+
```javascript
50+
/**
51+
* Definition for a binary tree node.
52+
* function TreeNode(val) {
53+
* this.val = val;
54+
* this.left = this.right = null;
55+
* }
56+
*/
57+
/**
58+
* @param {TreeNode} root
59+
* @return {boolean}
60+
*/
61+
var isBalanced = function (root) {
62+
if(!root) return true;
63+
let res = true;
64+
let dfs = (root) => {
65+
// 先遍历左子树,在遍历右子树
66+
let left = root.left && dfs(root.left) + 1;
67+
let right = root.right && dfs(root.right) + 1;
68+
// 判断是否是平衡二叉树,就看高度差是否大于1
69+
if (Math.abs(left - right) > 1) res = false;
70+
// 返回左右子树深度的最大值
71+
return Math.max(left, right);
72+
}
73+
dfs(root);
74+
return res;
75+
};
76+
```
77+
78+
79+
## 最后
80+
文章产出不易,还望各位小伙伴们支持一波!
81+
82+
往期精选:
83+
84+
<a href="https://github.com/Chocolate1999/Front-end-learning-to-organize-notes">小狮子前端の笔记仓库</a>
85+
86+
<a href="https://github.com/Chocolate1999/leetcode-javascript">leetcode-javascript:LeetCode 力扣的 JavaScript 解题仓库,前端刷题路线(思维导图)</a>
87+
88+
小伙伴们可以在Issues中提交自己的解题代码,🤝 欢迎Contributing,可打卡刷题,Give a ⭐️ if this project helped you!
89+
90+
91+
<a href="https://yangchaoyi.vip/">访问超逸の博客</a>,方便小伙伴阅读玩耍~
92+
93+
![](https://img-blog.csdnimg.cn/2020090211491121.png#pic_center)
94+
95+
```javascript
96+
学如逆水行舟,不进则退
97+
```
98+
99+

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /