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 left and right subtrees of every node differ in height by no 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.
题意
判断二叉树是否是平衡二叉树
思路1
- 满足左右子树深度差不超过1,左子树是平衡的,右子树是平衡的三个条件
代码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) {
if(root == NULL) return true;
int depth_left = dfs(root->left);
int depth_right = dfs(root->right);
return (abs(depth_left-depth_right) <= 1) && isBalanced(root->left) && isBalanced(root->right);
}
int dfs(TreeNode *node){
if(node == NULL) return 0;
int left = dfs(node->left);
int right = dfs(node->right);
return left > right ? (left + 1) : (right + 1);
}
};
递归求二叉树深度
int dfs(TreeNode *node){
if(node == NULL) return 0;
int left = dfs(node->left);
int right = dfs(node->right);
return left > right ? (left + 1) : (right + 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 {
private:
bool ans = true;
public:
bool isBalanced(TreeNode* root) {
maxDepth(root);
return ans;
}
int maxDepth(TreeNode *node) {
if(node == NULL) return 0;
int l = maxDepth(node->left);
int r = maxDepth(node->right);
if(abs(l - r) > 1) ans = false;
return 1 + max(l, r);
}
};