//树的深度
int TreeDepth(BTree* root)
{
int nLeft, nRight;
if(root == NULL)//必不可少的条件,递归的出口
return 0;
nLeft = TreeDepth(root->lchild);
nRight = TreeDepth(root->rchild);
return (nLeft > nRight) ? (nLeft + 1):(nRight + 1);
}
非递归写法
//树的深度
int TreeDepth(BTree* root)
{
if(root == nullptr)
return 0;
queue<TreeNode*> one,two;
one.push(root);
int res=0;
TreeNode* tmp=root;
while(!one.empty() || !two.empty())
{
if(!one.empty())
{
while(!one.empty())
{
tmp=one.top();
if(tmp->left);
two.push(tmp->left);
if(tmp->right)
two.push(tmp->left);
one.pop();
}
res++;
}
if(!two.empty())
{
while(!two.empty())
{
tmp=two.top();
if(tmp->left);
one.push(tmp->left);
if(tmp->right)
one.push(tmp->left);
two.pop();
}
res++;
}
}
return res;
}