C ++-如何查找n元树的给定节点的深度

Class Tree {
  Node* root
public:
  // member functions  
};
Class Node {
  int data;
  int numChildren;
  Tree* childrens // array of trees
};

我想计算树中给定节点的深度。到目前为止,这是我的尝试:

int Tree::getDepth(const int& data) const {
    if (!root) return -1; // empty tree

    if (root->data == data) return 0; // data found
    for (int i = 0; i < root->numChildren; ++i) // recursive
        return 1 + root->childrens[i].getDepth(data);

    return -1; // data not found
}

但这会造成麻烦。首先,我必须检查根是否为nullptr,并且在递归步骤中,如果根在满足所需节点之前遇到空子树,则计算将是错误的。您能给我一些解决这个问题的提示吗?

评论
  • 兔小乖
    兔小乖 回复
    int Tree::getDepth(const int& data) const {
        if (root) {
            if (root->data == data) return 0; // data found
            for (int i = 0; i < root->numChildren; ++i) // recursive
                return 1 + root->childrens[i].getDepth(data);
        }
        return -1; // empty tree or data not found
    }