思路
求解树的高度,是基于非递归实现树的遍历。树每往下遍历一次,栈顶向上加一,记录栈指针top,并使用变量maxDepth记录遍历过程中栈指针的最大值,此最大值,就是树的深度。
代码实现
//Bitree 表示树的节点结构
int FindHigh(BiTree T)
{
Bitree s[maxSize];
int top = 0;
//模拟栈结构。
int maxDepth = 0;
Bitree p = T;
while(p || top > 0)
{
if(p)
{
s[top++] = p;
p = p->lchild;
if(top > maxDepth)
maxDepth = top;
}
else
{
p = s[--top];
p = p->rchild;
}
}
return maxDepth;
}
参考王道书中的解释