update 110: add solution2

This commit is contained in:
ShusenTang 2020-02-13 19:58:53 +08:00
parent 49cf494e65
commit 6c6ed1b7d1

View File

@ -1,11 +1,21 @@
# [110. Balanced Binary Tree](https://leetcode.com/problems/balanced-binary-tree/description/) # [110. Balanced Binary Tree](https://leetcode.com/problems/balanced-binary-tree/description/)
# 思路 # 思路
## 思路一
一棵非空树是平衡二叉树的充要条件是: 一棵非空树是平衡二叉树的充要条件是:
* 其左右子树的高相差不超过1 * 其左右子树的高相差不超过1
* 且左右子树都是平衡二叉树。 * 且左右子树都是平衡二叉树。
因此是一个递归算法。 因此可考虑用一个递归算法,为此还需要一个递归算法求某树的高。
## 思路二
思路一的代码十分简洁,但是要注意一个节点会被重复遍历多次因此不是最优的算法。为此我们可以考虑用类似后序遍历的思路,在判断左右子树是否是平衡的同时还需要返回左右子树的高(可以通过传入引用实现),这样就可以不用再递归求左右子树的高了,即整个过程只遍历一遍节点。
# C++ # C++
## 思路一
``` C++ ``` C++
class Solution { class Solution {
private: private:
@ -20,3 +30,28 @@ public:
} }
}; };
``` ```
## 思路二
``` C++
class Solution {
private:
bool helper(TreeNode* root, int &height){
if(!root){
height = 0;
return true;
}
int l_h = -1, r_h = -1;
if(helper(root -> left, l_h) && helper(root -> right, r_h)){
// 此时l_h和r_h已被正确赋值为左右子树的高
height = 1 + max(l_h, r_h);
return abs(l_h - r_h) <= 1;
}
return false;
}
public:
bool isBalanced(TreeNode* root) {
int height = -1;
return helper(root, height);
}
};
```