【发布时间】:2020-12-10 18:30:34
【问题描述】:
我有以下 BST 供参考。 BST
假设最小值:9,最大值:20 它满足所有条件,对于每个节点(X),左子树中的所有节点都小于,右子树中的所有节点都大于X的值。
我无法创建一个打印所有值的函数(成员函数,因此它可以访问根节点)。具体来说,假设我当前的节点是 10,但我仍然需要检查左右子树。我无法传递参数中的节点(otherwise I could do something like this?),所以我必须实现这个功能
void printBetween(int min, int max);
此外,该函数应该只访问值可能有效的子树。
假设节点结构如下所示:
struct Node{
T data_;
Node* left_;
Node* right_;
Node(const T& data, Node* left=nullptr, Node* right=nullptr){
data_=data;
left_=left;
right_=right;
}
};
如果左孩子和右孩子的值都在最小值和最大值之间,我该怎么办?
void printBetween(int min, int max){
// left child: smaller than
// right child: bigger than
// This function prints every value in the tree that is between min and max inclusive.
if( root_ == nullptr)
cout << "No values found" << endl;
Node* currNode = root_;
// check until currNode is a valid node
while(currNode != nullptr){
// print value if currNode's data value is between min and max inclusive,
if(currNode->data_ > min && currNode->data_ <= max){
cout << "Value: " << data_ << "," << endl;
fnd = true;
// since it falls in the range, have to check both children
// not sure what to do here??
if(currNode != nullptr && currNode->left_->data_ > min && currNode->left_->data_ <= max){
currNode = currNode->left_;
} else if(currNode != nullptr && currNode->right_->data_ > min && currNode->right_->data_ <= max){
currNode = currNode->right_;
}
}
// current node's data is too big, so go to its left child
if(currNode->data_ > max){
currNode = currNode->left_;
}
// current node's data is too small, so go to its right child
else if(currNode->data_ < min){
currNode = currNode->right_;
}
}
}
【问题讨论】: