24.平衡二叉树
题目内容:
代码及思路:
注意两个重要判断线索:
1.高度平衡:每个节点 的左右两个子树的高度差的绝对值不超过1
2.为二叉树
因此利用递归的思想分别对左右子树计算高度
/**
* 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:
int Depth(TreeNode* root) //计算树的高度
{
if(root==nullptr)
return 0;
int left_depth=Depth(root->left);
int right_depth=Depth(root->right);
return (left_depth>right_depth)?left_depth+1:right_depth+1;
}
bool isBalanced(TreeNode* root) {
if(root==nullptr)
return true;
if(abs(Depth(root->left)-Depth(root->right))>1)
return false;
return isBalanced(root->left)&&isBalanced(root->right);
}
};