我想出了用于查找树高的前序遍历。
void preHeight(node * n)
{
int max = 0,c = 0;
while(1)
{
while(n)
{
push(n);
c++;
if(c>max)
max = c;
n= n->left;
}
if (isStackEmpty())
return max;
n = pop();
if(n->right) //Problem point
c--;
n=n->right;
}
}
我得到了正确的高度,但我不确定我的方法是否正确。我所做的是将我的计数器递增c
到最左边的节点,然后,如果我向上移动,我会减少它以防我需要向右移动,然后重复整个练习。那是对的吗?