平衡二叉树
![在这里插入图片描述](https://img-blog.csdnimg.cn/20191008184551929.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L2xpdXl1Y2hlbjI4MjgyOA==,size_16,color_FFFFFF,t_70)
int MAX(int a,int b)
{
return a > b ? a : b;
}
int getHeight(struct TreeNode *root){
if(root == NULL){
return 0;
}
int left =getHeight(root->left);
int right =getHeight(root->right);
return MAX(left,right)+1;
}
bool isBalanced(struct TreeNode* root){
if(root == NULL){
return true;
}
bool is_left_balance =isBalanced(root->left);
if(is_left_balance == false){
return false;
}
bool is_right_balance =isBalanced(root->right);
if(is_right_balance == false){
return false;
}
int left_height = getHeight(root->left);
int right_height = getHeight(root->right);
int diff =left_height-right_height;
if(diff >= -1 && diff <=1){
return true;
}else{
return false;
}
}
根据二叉树创建字符串
![在这里插入图片描述](https://img-blog.csdnimg.cn/20191008185728678.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L2xpdXl1Y2hlbjI4MjgyOA==,size_16,color_FFFFFF,t_70)
class Solution {
public:
string tree2str(TreeNode* t) {
if(t==nullptr)
return "";
stringstream ss;
function<void(TreeNode*)> helper = [&ss, &helper](TreeNode* t){
ss<<t->val;
if(t->left==nullptr){
if(t->right!=nullptr){
ss<<"()(";
helper(t->right);
ss<<')';
}
}
else if(t->right==nullptr){
ss<<'(';
helper(t->left);
ss<<')';
}
else{
ss<<'(';
helper(t->left);
ss<<")(";
helper(t->right);
ss<<')';
}
};
helper(t);
string s;
ss>>s;
return s;
}
};