版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
平衡二叉树
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
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;
//左右子树高度差要小于1
if(diff >= -1 && diff <=1){
return true;
}else{
return false;
}
}
根据二叉树创建字符串
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;
}
};