나무의 크기 (N)를 알고 있다고 가정합시다. 어쩌면 파일의 첫 번째 줄 일 수도 있습니다. 그렇지 않은 경우 인덱스 벡터의 동적 크기를 조정하기 위해이 방법을 쉽게 적용 할 수 있습니다. 이 반 의사가 있습니다 : 이유 node = index[nodeID]
이 아닌 NULL로 보장됩니다
// Only needed while parsing the file
std::vector<Node*> index(N, NULL);
// We can always create the root node.
// This simplifies the while loop below.
index[0] = createNode(0);
while (!in.eof()) {
int nodeID = -1, leftID = -1, rightID = -1;
parseNode(in, &nodeID, &leftID, &rightID);
// Guaranteed to be non-NULL
Node* node = index[nodeID];
// if leftID or rightID is -1, createNode()
// will simply return NULL.
index[leftID] = createNode(leftID);
index[rightID] = createNode(rightID);
node->setLeftChild(index[leftID]);
node->setRightChild(index[rightID]);
}
때문에 읽기 사전 주문 색인/쓰기 /이다. 우리는 처음에 루트 노드를 미리 만들었고 다른 모든 노드는 부모에 의해 왼쪽 또는 오른쪽 자식으로 만들어졌습니다.
편집 : 우리는 풀 마스터 인덱스가 필요 없다는 것을 깨달았습니다. 잠재적 우익 노드를 저장하여 스택으로 확장하면됩니다. 당신이 예약 주문 탐색과 같은 이진 검색 트리를 저장하는 경우 당신이 그들을 읽을
// Candidate right-child nodes to expand
std::stack<Node*> rightNodes;
// Pre-create the root node as "left child"
Node* left = createNode(0);
while (!in.eof()) {
// We already know the next node. It is the previous
// node's left child (or root), or the nearest
// parent's right child.
Node* node;
if (left != NULL) {
node = left;
}
else {
node = rightNodes.top();
rightNodes.pop();
}
parseLine(in, &nodeID, &leftID, &rightID);
assert(node->ID() == nodeID);
// if leftID or rightID is -1, createNode()
// will simply return NULL.
left = createNode(leftID);
Node* right = createNode(rightID);
node->setLeftChild(left);
node->setRigthChild(right);
if (right != NULL) {
rightNodes.push(right);
}
}
왜 나무를 이전과 똑같이 원하십니까? 순서대로 노드를 저장하면 밸런스 이진 탐색 트리로 다시 읽을 수 있습니다. –