BST高度算法如何计数?

问题描述 投票:-1回答:1
int BianaryTree<T>::height(Node<T>* A){
    root = A;
    if(root==nullptr){
        return 0;
    }
    else {
        int lHeight=height(root->left); //how is int counting here?
        int rHeight=height(root->right);
        return max(lHeight, rHeight)+1;
    }
}

因此,据我了解,这是标准的二叉搜索树高度算法。我的主要问题是,如何将recursd函数存储在int变量中以“计算”树的高度?据我所知,所有此函数返回的都是0。

int BianaryTree :: height(Node * A){root = A; if(root == nullptr){返回0; } else {int lHeight = height(root-> left); //这里的int如何计数? ...

c++ algorithm binary-search-tree
1个回答
0
投票

每个递归分支最终将导致返回值为零,但它返回的是左,右高度的最大值加1。该加1是至关重要的,如果没有,则整个递归的返回值确实为零,但有了它,您便得到了期望的高度。

© www.soinside.com 2019 - 2024. All rights reserved.