简体   繁体   中英

c++ how to get depth of a binary tree recursively

I wrote a code that suposed to return the depth of a binary tree from the root to the node who called the function. using recursive way but I faced a problem about how to count the number of times that the function gets called so I whould know how much convexity I passed. Someone know how can I do that?

int BSNode::getDepth(const BSNode& root) const
{
    if (this != nullptr)
    {
        if (root.getData() > this->_data)
        {
            this->getDepth(*root.getRight());
        }
        else if (root.getData() < this->_data)
        {
            this->getDepth(*root.getLeft());
        }
        else if (root.getData() == this->_data)
        {
            // return the number that the function counted
        }
    }
    else
    {
        return 0;
    }
}

You should at least return something in every case. And when you arrive at the intended node (having the data you are looking for), then return 0. In all other cases, return what you get from recursion plus 1. If the value is not found then indeed -1 should be returned. And if this -1 is coming back from recursion, it should be returned like that also to the caller (without adding 1).

Here is the code adapted:

int BSNode::getDepth(const BSNode& root) const
{
    int temp;
    if (this != nullptr)
    {
        if (root.getData() > this->_data)
        {
            temp = this->getDepth(*root.getRight());
            return temp == -1 ? -1 : temp + 1;
        }
        else if (root.getData() < this->_data)
        {
            temp = this->getDepth(*root.getLeft());
            return temp == -1 ? -1 : temp + 1;
        }
        else if (root.getData() == this->_data)
        {
            return 0;
        }
    }
    else
    {
        return -1;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM