당신은 단지
가의 2 스택 시작하자 2 스택을 ... 사용하여이 작업을 수행 할 수있다, (1) (예를 들어, 당신이 방문해야 노드를 포함) 간단한 할 일 스택이고, 다른 하나는 결과와 중첩된다.
루트 노드로 시작하고 노드가 범위 내에 있으면 결과 스택에 밀어 넣고 두 자식을 모두 실행 스택으로 밀어 넣습니다. 만약 범위를 벗어나면 2 가지 경우가 발생할 수 있습니다 : 1.) 범위 내에서 가장 작은 값보다 작습니다. - 바로 가기 스택에 오른쪽 자식을 넣으십시오. 2) 우리 범위에서 가장 큰 값보다 큽니다 -> 잭 스택에
좋아요 그래서 몇 가지 유용한 알고리즘이 점을 만들 수 있습니다 :이 언어와 같은 C 단지 의사 코드 ++이라고
List<BSTNode*> FindAllInRange(BSTNode* root, int low, int high)
{
Stack<BSTNode*> todo; //< Todo stack
Stack<BSTNode*> results; //< Results stack
// Start with root node
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();
}
참고.
단지 참고 사항입니다. 6-> 7-> 8-> 10-> 13일까요? ... Lemme은 그 중간의 방법에 대한 해답을 생각합니다. – ZarakiKenpachi