I need to find the in-order successor in a binary search tree. For example, given a tree with format:
4
/ \
2 7
and passing a search value of 2, the in-order successor would be 4.
Relevant Code:
template <typename T, typename Compare=std::less<T>>class BinarySearchTree {
private:
struct Node {
// Default constructor - does nothing
Node() {}
// Custom constructor provided for convenience
Node(const T &datum_in, Node *left_in, Node *right_in)
: datum(datum_in), left(left_in), right(right_in) { }
T datum;
Node *left;
Node *right;
};
And here's my function searching for the in-order successor
static Node * min_greater_than_impl(Node *node, const T &val, Compare less) {
// base case: empty tree
if (node == nullptr) {
return nullptr;
}
// base case: no such element exists
if (less((max_element_impl(node))->datum, val) || (!less((max_element_impl(node))->datum, val)
&& !less(val, (max_element_impl(node))->datum))){
return nullptr;
}
// recursive case: go right
if (less(node->datum, val)) {
if (node->right != nullptr) {
return min_greater_than_impl(node->right, val, less);
}
}
// recursive case: go left
else if (less(val, node->datum)) {
if (node->left != nullptr) {
return min_greater_than_impl(node->left, val, less);
}
}
// recurisve case: nequal to node, go right
else {
if (node->right != nullptr) {
return min_greater_than_impl(node->right, val, less);
}
}
return node;
}
Now, I believe the issue is that my function is not recognizing when it is actually at the desired node. I'm thinking that I need to check for this in maybe an extra base case or perhaps another else if statement at the end of the function. However, I can't think of how to do this without making a recursive call on the current node, but that would just end up in infinite loop.
The easiest way to do it is to add a parent pointer. Then to get "next", go up until you find the sibling.
If you can't use a parent, often for good reasons (eg the tree allows duplicate sub-branches), you have to keep your own stack of parent objects as you descend. To get the next object, if we are a left leaf, it is the parent, if we are a right leaf then if parent is a left leaf, it is the grandparent, otherwise we need to go up and check if grandparent is a left leaf of the great-grandparent. (If we hit the root, then our node was the last right leaf).
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.