我先写了个dfs函数去递归遍历左右子树,每遍历左子树一个节点,count1即++
遍历右子树节点count2++
直到左右子树遍历为空,结束递归。
此时count1+count2就是树的高度。
知道了树的高度就可以求平衡因子了。
左子树的高度-右子树的高度如果>1.那就不是平衡树
class Solution {
public:
int count1=0;
int count2=0;
void dfs(TreeNode* root)
{
if(root==nullptr)return;
if(root->left==nullptr||root->right==nullptr)return;
if(root->left)
{
count1++;
dfs(root->left);
}
if(root->right)
{
count2++;
dfs(root->right);
}
}
bool isBalanced(TreeNode* root) {
dfs(root);
int bf=count1-count2;
if(bf<-1||bf>1)return false;
else return true;
}
};
但是通不过,原因是count1和count2并不能把子树树高统计出来。
另外,平衡因子判断树高的方法也错了
正确方法
后序遍历求高度,高度判断是否平衡 | LeetCode:110.平衡二叉树_哔哩哔哩_bilibili
判断是否平衡我们可以通过平衡因子来判断。
平衡因子又是根据树高之差来判断是否平衡的。
所以我们先求出树高。
我们写一个求 树高函数
求树高一般都用后序,从叶子节点到根节点。
如果该二叉树只要一个节点,那么树高就为1。
递归遍历左右子树,如果左右子树树高为-1,说明不平衡,不再递归,向上返回。
如果遍历完都没有-1,那就用abs(左子树树高-右子树树高),如果结果为-1,那么就把树高=-1给平衡因子
否则就把左右子树树高最高的那个加1给给平衡因子。
class Solution {
public:
int treeheight(TreeNode* root)
{
if(root==nullptr)return 0;//一个节点都没有高度为0
int leftheight=treeheight(root->left);
if(leftheight==-1)return -1;//已经不平衡,不再向下遍历,向上返回。
int rightheight=treeheight(root->right);
if(rightheight==-1)return -1;//已经不平衡,不再向下遍历,向上返回。
int result=0;
if(abs(leftheight-rightheight)>1)result=-1;
else result=1+max(leftheight,rightheight);
return result;
}
bool isBalanced(TreeNode* root) {
//平衡树的特性:两个子树高度差不超过1 我们利用平衡因子来求
return treeheight(root) == -1 ? false : true;
}
};