第一百一十题:(判断是否为平衡二叉树)自己写的
1.边界情况:
根结点为空。
2.思路:
利用递归返回结点的高度,在其中加入判断是否平衡,如果不平衡就返回-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:
int getTreeHight(TreeNode* root){
if (root == NULL)
return 0;
int h_L = 0, h_R = 0;
h_L = getTreeHight(root->left);
if (h_L == -1)
return -1;
h_L++;
h_R = getTreeHight(root->right);
if (h_R == -1)
return -1;
h_R++;
if (abs(h_L - h_R) > 1)
return -1;
else
return max(h_L, h_R);
}
bool isBalanced(TreeNode* root) {
if (root == NULL)
return true;
if (getTreeHight(root) == -1)
return false;
else
return true;
}
};
static const int _ = []() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
return 0;
}();