【发布时间】:2014-06-05 18:31:25
【问题描述】:
我想出了一个前序遍历来找到一棵树的高度。
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 直到最左边的节点,然后,如果我向上移动,我会减少它以防我需要向右移动,然后重复整个练习。对吗?
【问题讨论】:
-
while(n->child) { depth++; n = n->child },基本上,如果你假设树是平衡的。 -
为什么不想递归?
标签: c tree tree-traversal preorder