初阶的玩法
首先就是要写一个计算树深度的一个函数。
int TreeDepth(struct TreeNode* root)
{
if(root == 0)
return 0;
int left = TreeDepth(root->left);
int right = TreeDepth(root->right);
return left>right?left+1:right+1;
}
这个很简单就是一个递归。(时间复杂度为o(N))
在主函数里面再写一个递归就解决问题了
bool isBalanced(struct TreeNode* root){
if(root == NULL)
return true;
int gap = TreeDepth(root->left) - TreeDepth(root->right);
if(abs(gap)>1)
return false;
return isBalanced(root->left)&&isBalanced(root->right);
}
这里要遍历每一个结点时间复杂度也为o(N)
初阶的玩法时间复杂度就是O(N*N)
真男人,要玩就玩进阶的!!!
进阶玩法
先卖个关子,你有什么办法将 这个时间复杂度将为O(N)呢?
其实只要将先序改为后序就行。
拿这个二叉树来举例
9的左子树和右子树都为空
利用后序:左子树、右子树、根。先算左子树将左子树验证完,在验证右子树,当两个全为真时再进行根的判断,之后再返回根的深度,上面的就不用再次计算了
bool _isBalanced(struct TreeNode* root, int* pDepth)
{
if(root == NULL)
{
*pDepth = 0;
return true;
}
else
{
int leftDepth = 0;
if(_isBalanced(root->left, &leftDepth) == false)
return false;
int rightDepth = 0;
if(_isBalanced(root->right, &rightDepth) == false)
return false;
if(abs(leftDepth-rightDepth)>1)
return false;
*pDepth = leftDepth>rightDepth?leftDepth+1:rightDepth+1;
return true;
}
}
bool isBalanced(struct TreeNode* root){
int Depth = 0;
return _isBalanced(root,&Depth);
}