判断该树是不是平衡树
1. 递归
- 空间复杂度:深度 log2N(表示log以2为底N的对数)
- 时间复杂度:O(n^2)
(递归的次数*每次递归的次数)
每个节点的遍历*高度(也是遍历整个树)
代码:
int _Depth(Node* root)
{
if (NULL == root)
return 0;
int left = _Depth(root->_left)+1;
int right = _Depth(root->_right) + 1;
return left > right ? left : right;
}
bool IsBalance()
{
int depth = 0;
return _IsBalance(_root,depth);
}
//递归——时间复杂度n^2
bool _IsBalance(Node* root)
{
//递归的终止条件
if(root == NULL)
{
return true;
}
int leftHeight = Height(root->_left);
int rightHeight = Height(root->_right);
return abs(rightHeight-leftHeight) < 2
&& _IsBalance(root->_left)
&& _IsBalance(root->_right);
}
2.优化
- 空间复杂度:深度 log2N(表示log以2为底N的对数)
- 时间复杂度:O(n)
主要思想:高度每次重复遍历,从叶子节点开始判断是否为平衡树,然后统计其高度,这样到了根,就证明该树是平衡树。
//优化——时间复杂度n——高度只遍历一次
bool _IsBalance(Node* root,int& depth)
{
if(root == NULL)
{
depth = 0;
return true;
}
int leftdepth = 0;
int rightdepth = 0;
if(_IsBalance(root->_left,leftdepth) == false)
return false;
if(_IsBalance(root->_right,rightdepth) == false)
return false;
if(rightdepth - leftdepth != root->_bf)
{
cout << root->_key << "平衡因子异常" << endl;
return false;
}
depth = leftdepth > rightdepth ? leftdepth+1 : rightdepth+1;
}