思路:若当前节点为空,返回true(即当前节点算平衡二叉树),否则计算当前节点的左子树与右子树层数差值,如果差值的绝对值大于1(即当前节点不为二叉树),则直接返回false,然后再继续往左子树和右子树走,求他们结果的与(即只有当两子树都为平衡二叉树,这棵树才会是一棵平衡二叉树,若有一支不满足则就不会成为平衡二叉树)
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
bool isBalanced(TreeNode* root) {
if(root==nullptr)
return true;
if(abs(Count(root->left)-Count(root->right))>1)
return false;
return isBalanced(root->left)&&isBalanced(root->right);
}
int Count(TreeNode* &root)
{
if(root==nullptr)
return 0;
return max(Count(root->left),Count(root->right))+1;
}
};
看了解题另一种思路:从下往上,计算每个节点的左右子树高度,如果为非平衡二叉树或左右子树高度得-1,则返回-1,否则返回此节点的高度。若最终结果大于-1,则为平衡二叉树,反正不为平衡二叉树。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int height(TreeNode* &root)
{
if(root==NULL)
return 0;
int lheight=height(root->left);
int rheight=height(root->right);
if(lheight==-1||rheight==-1||abs(rheight-lheight)>1)
return -1;
else
return max(rheight,lheight)+1;
}
bool isBalanced(TreeNode* root) {
return height(root)>-1;
}
};