这是我的第一个答案,所以我很抱歉我的英语不好。
在每一个这样的递归问题中,考虑问题的最简单方法是:
-解决“基本情况”,这通常是微不足道的。 (对于大多数数据结构,这通常是空结构或单元素结构。)
-根据构成结构的子结构来解决一般情况,(例如,在考虑树时,这是考虑到左子树和右子树来完成的)假设您可以依靠子结构的解决方案。
我确定我没有很好地解释它,所以让我做一个简单的例子:
我们要计算 BST 中元素的总数。
解决方法是这样的:
int countElement(struct treeNode* node)
{
if(node == null)
{
//we are in the base case: the tree is empty, so we can return zero.
return 0;
}
else
{
/*the tree is not empty:
We return 1 (the element that we are considering)
+ the elements of the left subtree
+ the elements of the right subtree.*/
return 1 + countElement(node->left) + countElement(node->right);
}
}
如果您清楚这一点,我们可以继续处理您的请求:
int rangeSearch(struct treeNode * node, int leftBound, int rightBound)
{
if(node == 0)
{
//base case: the tree is empty, we can return 0
return 0;
}
else
{
/*our tree is not empty.
Remember that we can assume that the procedure called on
the left and right child is correct.*/
int countLeft = rangeSearch(node->left, leftBound, rightBound);
int countRight = rangeSearch(node->right, leftBound, rightBound);
/*So what we have to return?
if the current node->item is between leftbound and rightbound,
we return 1 (our node->item is valid) + rangeSearch called
on the left and child subtree with the same identical range.*/
if(node->item > leftBound && node->item < rightBound)
{
/*the element is in the range: we MUST count it
in the final result*/
return 1 + countLeft + countRight;
}
else
{
/*the element is not in the range: we must NOT count it
in the final result*/
return 0 + countLeft + countRight;
}
}
}
请记住,所有的关键部分是,如果你定义和解决了基本情况,那么当你考虑更大的结构时,你可以假设你的递归过程调用的 SUBSTRUCTURE 做正确的事情并返回正确的价值。