2012-10-21 121 views
0

我想创建一个方法,告诉我一个二叉树的高度,最简单的方法是使用递归,但由于某种原因,我的一个变量即使重新设置,即使我以为我在检查所以它会保持不变...
这里是我的代码
递归和常量变量

template<class T> 
int findHeight(binaryTreeNode<T> , int leftHeight, int rightHeight, 
     int maxHeight) { 
    if (leftHeight >= rightHeight && leftHeight >= maxHeight) { 
     maxHeight = leftHeight; 
    } 
    else if (leftHeight < rightHeight && rightHeight >= maxHeight) { 
     maxHeight = rightHeight; 
    } 
    if (t != NULL) { 
     cout << "current leftHeight " << leftHeight << " current rightHeight " 
       << rightHeight << " current maxHeight " << maxHeight << endl; 

     findHeight(t->leftChild, ++leftHeight, rightHeight, maxHeight); 
     findHeight(t->rightChild, leftHeight, ++rightHeight, maxHeight); 
    } 
    return ++maxHeight; 
} 

这是当我尝试这样做我已经得到的输出:

current leftHeight 0 current rightHeight 0 current maxHeight 0 
current leftHeight 1 current rightHeight 0 current maxHeight 1 
current leftHeight 2 current rightHeight 0 current maxHeight 2 
current leftHeight 2 current rightHeight 1 current maxHeight 2 
current leftHeight 1 current rightHeight 1 current maxHeight 1 
current leftHeight 2 current rightHeight 1 current maxHeight 2 
current leftHeight 3 current rightHeight 1 current maxHeight 3 
Returned value = 1 

任何人都可以帮我吗?我该如何做到这一点,以便maxHeight不会被重置,并且会在整个递归过程中随时保持找到的最大值。

+0

注意你的矛盾。常量不是可变的,变量不是(必然)是常量。你的问题是你正在通过一个值来传递一个变量,这会产生一个副本。更改副本不会更改从中复制的变量。 –

回答

2

事情是简单的:

int findHeight(binaryTreeNode<T> *t){ 
    return t ? 1 + MAX(findHeight(t->leftChild), findHeight(t->rightChild)) : 0; 
} 

在你的代码,因为maxheight是按值传递,而不是参考有问题。

0

函数参数具有自动存储持续时间(通常称为“在堆栈上”)。这意味着每个致电findHeight的电话都有自己的变量,名称为maxHeight。您在其生命周期结束之前增加其中一个局部变量。尽管您返回递增值,但您不会在递归调用中使用该返回值。

可以使用引用参数,也可以使用两次递归调用的返回值。