我已经编写了这个函数来查找二叉搜索树中最浅的叶子,它不是最好的,但它做的工作,叶子必须在找到它之后返回。C++在非常量指针函数中返回一个常量指针
它是不改变函数原型的必要条件。
我的问题是由以下
问题是我是回一个没有const的指针函数内部一个const指针评论指出,我张贴问题前,所有的问题,其中的类中的功能,我没有研究过它们,所以我不知道它是否与类之外的函数相同,有没有解决这个问题的方法?
struct Node {
int _data;
struct Node *_left;
struct Node *_right;
};
//-----------------------------------------------------------------------------------
struct Node *min_depth_leaf(const struct Node *root, int &depth) {
int left_depth;
int right_depth;
if (root == NULL) {
depth = INT32_MAX;
return NULL;
} else if (root->_left == NULL && root->_right == NULL) {
depth = 0;
return root;//<-------------- The problem lays here
} else if (root->_left != NULL || root->_right != NULL) {
struct Node *left_node = min_depth_leaf(root->_left, left_depth);
struct Node *right_node = min_depth_leaf(root->_right, right_depth);
if (right_depth < left_depth) {
right_depth += 1;
depth = right_depth;
return right_node;
} else {
left_depth += 1;
depth = left_depth;
return left_node;
}
}
return NULL;
}
感谢您接受我的答案。 –