BSTNode<Tkey,TValue>
노드로 구성된 이진 검색 트리 BST<Tkey,TValue>
을 만든 후이 노드에 대해 IEnumerable 인터페이스를 구현하려고합니다. I는 root
노드 _current
전달바이너리 검색 트리 IEnumerator.MoveNext() 탐색 순회가 아닌 재귀 적입니다. 어떻게?
public class BSTNodeEnumerator<TKey, TValue> : IEnumerator<BSTNode<TKey, TValue>> where TKey : IComparable<TKey>
{
private Stack<BSTNode<TKey, TValue>> _stack;
public BSTNodeEnumerator(BSTNode<TKey, TValue> root)
{
_stack = new Stack<BSTNode<TKey, TValue>>();
_current = null;
_root = root;
}
// ... rest of the implementation
}
열거 결과이다
이
는이BSTNodeEnumrator<Tkey,TValue>
내가 구축 방법이다. 또한 AVL BST처럼 부모 노드를 추적하지 않기 때문에이 스택을 사용하려고합니다.
이제는 열거자가 비 순차적 방식으로 트리를 순서대로 넘어가 길 원합니다. 결과적으로 BST의 특성으로 인해 정렬 된 열거 형을 가져와야합니다. 이는 달성하고자하는 바로 위대한 것입니다.
우리는이 C# 코드로 알고리즘을 변형 할 수있다 wikipedia article
iterativeInorder(node)
s ← empty stack
while (not s.isEmpty() or node ≠ null)
if (node ≠ null)
s.push(node)
node ← node.left
else
node ← s.pop()
visit(node)
node ← node.right
이 같이 의사 코드에서 주문 탐색에 대한 비 재귀 알고리즘 :
public BSTNode<Tkey,TValue> Next()
{
while (_stack.Count > 0 || _current != null)
{
if (_current != null)
{
_stack.Push(_current);
_current = _current.left;
}
else
{
_current = _stack.Pop();
BSTNode<Tkey,TValue> result = _current;
_current = _current.Right;
}
}
return result;
}
그러나이 아니다 내가 bool을 반환해야만하므로 bool MoveNext()
구현이 필요합니다. 적절한 노드에 _current
을 설정하면 true이고, 내가 끝에 있으면 false입니다.
public bool MoveNext()
을 어떻게 구현해야합니까? 내가 머리를 감쌀 수없는 주된 이유는 바로 을 bool MoveNext()
으로 변환하고 싶다면 단순히 BSTNode<Tkey,TValue> result = _current;
노드를 방문하는 대신 return true
을 입력해야하고 그 후에는 분명히 할 수없는 _current = _current.Right;
을 설정해야합니다.
그냥 HashSet 또는 Dictionary를 사용하지 않는 이유는 무엇입니까? –
자신의 IEnumerator를 만들어야합니까? 왜 그냥 GetEnumerator 함수가 당신의 임 플레멘 테이션을 리턴하는 것이 아니라'BSTNode result = _current;'라인에서'yield return _current;'를 수행하십시오. 나는 임 플레 션을 답으로 게시 할 것이다. –
@MatthewWhited - 확실히 .Net에 이미있는 것을 사용할 수 있습니다. 나는 단순히 배우려고합니다. 나는 또한 AVL 바이너리 나무와 skiplists와 지금 막 싸우고있다. 이해할 수 있다고 확신합니다. 내말은. 닷넷은 하늘에서 온 것이 아니야. – pijemcolu