mirror of
https://github.com/ShusenTang/LeetCode.git
synced 2024-09-02 14:20:01 +00:00
Create 110. Balanced Binary Tree.md
This commit is contained in:
parent
263233a3f1
commit
82bf920b54
22
110. Balanced Binary Tree.md
Normal file
22
110. Balanced Binary Tree.md
Normal file
@ -0,0 +1,22 @@
|
|||||||
|
# [110. Balanced Binary Tree](https://leetcode.com/problems/balanced-binary-tree/description/)
|
||||||
|
# 思路
|
||||||
|
一棵非空树是平衡二叉树的充要条件是:
|
||||||
|
* 其左右子树的高相差不超过1;
|
||||||
|
* 且左右子树都是平衡二叉树。
|
||||||
|
|
||||||
|
因此是一个递归算法。
|
||||||
|
# C++
|
||||||
|
``` C++
|
||||||
|
class Solution {
|
||||||
|
private:
|
||||||
|
int getDepth(TreeNode *root){
|
||||||
|
if(root == NULL) return 0;
|
||||||
|
return 1 + max(getDepth(root -> left), getDepth(root -> right));
|
||||||
|
}
|
||||||
|
public:
|
||||||
|
bool isBalanced(TreeNode* root) {
|
||||||
|
if(root == NULL) return true;
|
||||||
|
return (abs(getDepth(root -> left) - getDepth(root -> right)) <= 1) && isBalanced(root -> left) && isBalanced(root -> right);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
```
|
Loading…
Reference in New Issue
Block a user