# 创建一个单链列表，其中包含BST给定范围内的数字Creating a singly linked list that contains the numbers within a given range of a BST

## 2 个回复2

### ===============>>#1 票数：1 已采纳

``````List<BSTNode*> FindAllInRange(BSTNode* root, int low, int high)
{
Stack<BSTNode*> todo;              //< Todo stack
Stack<BSTNode*> results;           //< Results stack

todo.push(root);

// While we have nodes to process
while(todo.size() > 0)
{
// Get top node, and pop it from stack
BSTNode* curr = todo.top();
todo.pop();

// If its value is less than the lowest value in range
if(curr->value < low)
{
// Push right children if exists (as it may be higher than lowest value in range)
if(node->right)
todo.push(node->right);
}
// If its value is greater than the highest value in range
else if(curr->value > high)
{
// Push left children if exists (as it may be lower than highest value in range)
if(node->left)
todo.push(node->left);
}
// Otherwise (we're in range)
else
{
// Push current node to results stack
results.push(curr);

// If right node exists, push it on todo stack
if(node->right)
todo.push(node->right);

// If left node exists, push it on todo stack
if(node->left)
todo.push(node->left);
}
}

// Now you just have to convert the stack to list (and possibly sort it, reverse sort it, ...)
return results.ConvertToList();
}
``````

### ===============>>#2 票数：1

`````` (8) You start in root. `L` - go left.
(3) You are in (3). You go `LVR` for this node again - recurrence. `L`
(1) You are in (1). Now *again* `LVR`.
However there is no left node so we go to `V` - visit/print 1. Now `R` - no right node. End. By recurrence we go back to 3.
(3) - We're done with `L`. We do `V`. Print 3.
(3) - `R`.
(6) You are in (6) - `LVR` again. 'L'
(4) You are in (4) - `L` does not exists. Print 4. `R` does not exist. Back one level.
(6) - `V`. Print 6.
(6) - `R`.
You are in (7) - `L` does not exists. Print 7. `R` does not exist. Back one level.
(6) - `LVR` Done. Back one level.
(3) - `LVR` Done. Back one level.
(8) - `R`.
(10) You are in 10. `L` Does not exist.
(10) `V`. Print 10.
(10) `R`.
(14) You are in 14.
(14) `L`.
(13) You are in 13. `L` does not exists. Print 14. `R` does not exist. Back one level.
(14) `V`. Print 14.
(14) `R`. Does not exist. Back one level.
(10) Done with `R`. Back one level.
(8) Done with `R`. Back one level.
Haha we were on root node so we are done.
``````